首页 > 数据库 >EF Core 中原生SQL、存储过程、视图的使用

EF Core 中原生SQL、存储过程、视图的使用

时间:2023-04-28 17:34:33浏览次数:31  
标签:Core set like FromSqlRaw EF 视图 where select

包括EF Core中原型Sql的执行,包括存储过程和视图数据处理方法,同时包括参数化执行sql语句的注意事项。

原生Sql查询

原生sql查询使用如下两个方法进行,查询的结构只能映射到dbset关联的对象类型

DBSet.FromSqlRaw()
DBSet.FromSqlInterpolated()

可以使用部分linq扩展方法

.FromSqlRaw("select * from authors").FirstOrDefault(a=>a.Id==3)
.FromSqlRaw("select * from authors").OrderBy(a=>a.LastName)
.FromSqlRaw("select * from authors").Include(a=>a.Books)
.FromSqlRaw("select * from authors").AsNoTracking()

Find方法不受支持

避免Sql注入

参数化查询

.FromSqlRaw("select * fro mauthors where lastnmae like '{0}%'",lastnameStart).TagWith("Fromatted_Safe").ToList()
.FromSqlRaw($"select * fro mauthors where lastnmae like '{lastnameStart}%'").TagWith("Fromatted_Safe").ToList()
.FromSqlInterpolated($"select * fro mauthors where lastnmae like '{lastnameStart}%'").TagWith("Interpolated_Safe").ToList()

不安全的查询

string sql = $"select * fro mauthors where lastnmae like '{lastnameStart}%'";
.FromSqlRaw(sql).TagWith("Interpolated_Unsafe").ToList()
.FromSqlRaw($"select * fro mauthors where lastnmae like '{lastnameStart}%'").TagWith("Interpolated_Unsafe").ToList()
存储过程使用
EXEC thesproc param1,param2,param3

添加存储过程

add-migration AddStoredProc
public partial class AddStoredProc : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql(@"
        CREATE PROCEDURE dbo.AuthorsPublishedinYearRange
        @yearstart int,
        @yearend int
        AS
        select * from authors as a
        left join books as b  on a.authorid = b.authorId
        where Year(b.PublishDate) >=@yearstart and Year(b.PublishDate) <=@yearend
        ");
    }
    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.Sql(" drop procedure AuthorsPublishedinYearRange")
    }
}

执行存储过程

DBSet.FromSqlRaw("AuthorsPublishedinYearRange {0},{1}",1999,2010);
DBSet.FromSqlInterpolated($"AuthorsPublishedinYearRange {start},{end}");

不能使用的方法:Include

视图的使用方法

//示例,视图返回如下数据
public class AuthorByArtist
{
    public string Artist {get;set;}
    public string? Author {get;set;}
}
//1、定义Dbset
public virual DbSet<AuthorByArtist> AuthorByArtist {get;set;}
//2、设置Entity
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<AuthorByArtist>().HasNoKey()
    .ToView("AuthorByArtist");
    .....
}

没有主键,不能使用Find方法查询数据

数据库级别执行:Non-Query Raw SQL

_context.Database.ExecuteSQLRaw("update author set a.name = '{0}",newname);
_context.Database.ExecuteSQLRawAsync("update author set a.name = {0}",newname);

_context.Database.ExecuteSQLInterpolated(("update author set a.name = {newname}  where authorid = {id}");
_context.Database.ExecuteSQLInterpolatedAsync("update author set a.name = {newname}  where authorid = {id}");
//执行存储过程
_context.Database.ExecuteSQLRaw("DeleteCover {0}", coverId);

标签:Core,set,like,FromSqlRaw,EF,视图,where,select
From: https://www.cnblogs.com/LifelongLearning/p/17362755.html

相关文章

  • Core i7正式揭开面纱 性能完全测试
    虽然要到本月17日才会正式发布,但IntelCorei7系列四核心处理器的NDA保密协议已于今天中午到期,日本PCWatch再次凭借时差优势第一个发布了完整的评测.有关Corei7系列我们已经相当熟悉了.它们基于Intel的新一代微架构Nehalem,开发代号Bloomfield,首批登场的将有三款型号,具体规......
  • C++中关于默认构造函数(Default Constructor)
    读<<深度探索C++对象模型>>,第二章介绍了默认构造函数,自觉知识点虽基础但是很是被忽略,故作此文记录.关于基础概念不做介绍,先看代码#include<stdio.h>#include<string>classSample{public:intintVal;};classFoo{public:Foo(inta=1000):int......
  • CMakeLists---自定义变量-add_definitions()函数
    转载:https://blog.csdn.net/qq_35699473/article/details/115837708引言其实这个函数在安装一些库的时候,它的CMakeLists里面就有这样的函数。典型的就是opencv了。opencv安装时候有一些指令也是针对这个函数的,比如安装命令(随便搜索的):cmake ../opencv-3.4.1-DWITH_GTK_2......
  • ubuntu core
    /etc/default/apport---->1/etc/sysctl.conf<<kernel.core_pattern=/coredump/core-%e-%p-%t/sbin/sysctl-p查看路径/proc/sys/kernel/core_pattern ......
  • 《Effective C#》系列之(六)——提高多线程的性能
    一、综述《EffectiveC#》中提高多线程性能的方法主要有以下几点:避免锁竞争:锁的使用会导致线程阻塞,从而影响程序的性能。为了避免锁竞争,可以采用无锁编程技术,如CAS(Compare-And-Swap),Interlocked等。使用ThreadPool:ThreadPool是.NETFramework提供的一个线程池,它可以......
  • Makefile 只修改了.h头文件,编译为什么不起作用?
    M,-MM,-MMD,-MF,-MT区别https://programmer.group/gcc-m-mm-mmd-mf-mt.htmlRef加-MMD选项解决头文件编译生效https://cloud.tencent.com/developer/article/1837814gcc预处理选项https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html......
  • ts文件可以操控vue文件里面的ref元素吗
    ts文件可以操控vue文件里面的ref元素吗exportconstfileInputElement=ref<null|HTMLElement>(null);我在ts文件里获得fileInputElement我能操控vue文件里ref为fileInputElement的元素吗import{messagesRef,}from"@/core/helpers/chat";exportconstmessagesRef......
  • 产品质量管理利器,华为云发布CodeArts Defect缺陷管理服务
    摘要:近日,华为云CodeArtsDefect缺陷管理服务正式上线,提供结构化缺陷跟踪流程和标准化的质量度量模型。本文分享自华为云社区《产品质量管理利器,华为云发布CodeArtsDefect缺陷管理服务》,作者:华为云头条。美国管理学家彼得曾经说过,“决定水桶盛水量多少的关键因素不是其最长的板......
  • .netcore 使用Quartz定时任务
    这是一个使用.NETCore和Quartz.NET实现定时任务的完整示例。首先确保已经安装了.NETCoreSDK。接下来按照以下步骤创建一个新的控制台应用程序并设置定时任务:创建一个新的.NETCore控制台应用程序:dotnetnewconsole-nQuartzDemocdQuartzDemo通过NuGet添加......
  • 《Effective C#》系列之(零)——概要
    把全书的内容讲述完整可能需要很长时间,我可以先回答主要目录和核心的内容。如果您有任何特定问题或需要更详细的解释,请告诉我。《EffectiveC#》一书共包含50条C#编程建议,以下是其中的一些主要目录:1.理解C#的基础知识2.使代码更易于阅读和理解3.利用C#语言的新功能4.改进异......