EntityFramework Core入门教程-11-使用原生的SQL

原文:https://blog.csdn.net/weixin_40719943/article/details/106964258


一、原生SQL查询

DbSet提供了四个方法用来执行原生的sql查询
(一)执行非字符串插值的字符串

1 FromSQLRaw("select *...");
2 FromSQLRawAsync("select * ...");

(二 )执行字符串插值的字符串,用C#6 新语法,用$

C#6.0新语法:
3 FromSQLIntepolated($"selct * from where x={var}");
4 FromSQLIntepolatedAsync($"selct * from where x={var}");

例如:

 var leagues = context.Leagues
             .FromSqlRaw("select * from efcoredemo.Leagues")
             .ToList();

原生sql查询要求:
1 必须返回Enitty类型的所有属性,即必须使用 Select * …
2 字段名和Entity属性名配置
3 无法包含关联的数据
4 只能查询已知的Entity

二、执行非查询类SQL

一、执行非字符串插值字符串

Context.Database.ExecuteSQLRaw()
Context.Database.ExecuteSQLRawAsync();

二、执行字符串插值字符串

Context.Database.ExecuteSQLInterpolated()
Context.Database.ExecuteSQLInterpolatedAsync()
原文地址:https://www.cnblogs.com/springsnow/p/13404269.html