[英]Execute RAW SQL on DbContext in EF Core 2.1
I have researched this and always found examples like this: 我对此进行了研究,并始终找到如下示例:
var blogs = context.Blogs
.FromSql("SELECT * FROM dbo.Blogs")
.ToList();
The problem is, I don't want to run my raw SQL on the Blogs table. 问题是,我不想在Blogs表上运行原始SQL。 Basically, I want to implement an interface like this: 基本上,我想实现这样的接口:
bool ExecuteNonSafeSql(
string connectionString,
string sql);
Is there a way to do that with DbContext? 有没有办法用DbContext做到这一点?
At the time of writing (EF Core 2.1), there is no way to execute arbitrary secuence returning SQL command. 在撰写本文时(EF Core 2.1),尚无办法执行返回 SQL命令的任意安全性 。
Only entity types and Query Types are supported via FromSql
. 通过FromSql
仅支持实体类型和查询类型 。
So the closest solution is to define query type (a class holding the query result) and use FromSql
, but it's not generic - the query types must be registered in the DbContext
via fluent API and the method should receive a generic argument specifying that type, eg 因此,最接近的解决方案是定义查询类型(一个保存查询结果的类)并使用FromSql
,但这不是通用的-查询类型必须通过fluent API在DbContext
注册,并且该方法应接收一个通用的参数来指定该类型,例如
class ResultType
{
// ...
}
then 然后
modelBuilder.Query<ResultType>();
and finally 最后
db.Query<ResultType>().FromSql(...)
Note that Database.ExecuteSqlCommand
can execute arbitrary SQL, but can't be used to return sequence ( IEnumerable<T>
, IQueryable<T>
). 请注意, Database.ExecuteSqlCommand
可以执行任意SQL,但不能用于返回序列( IEnumerable<T>
, IQueryable<T>
)。
You can use context.Database.ExecuteSqlCommand()
to execute sql. 您可以使用context.Database.ExecuteSqlCommand()
执行sql。
If you want to use SqlCommand
you can get the connection by 如果要使用SqlCommand
,可以通过以下方式获取连接
var cnn = (SqlConnection) context.Database.GetDbConnection();
cnn.Open();
using (var cmd = new SqlCommand(sql, cnn))
using (var rdr = cmd.ExecuteReader(CommandBehavior.SingleResult))
You can use Database.SqlQuery()
directly to context. 您可以将Database.SqlQuery()
直接用于上下文。
Here i create a generic function that can execute your query directly with target to Database rather than entity. 在这里,我创建了一个泛型函数,可以直接针对数据库而不是实体直接执行查询。
public static List<T> Execute<T>(MyDbContext context, string query) where T : class
{
var result = context.Database
.SqlQuery<T>(query)
.ToList();
return result;
}
You can use above function like 您可以使用上述功能,例如
var blogs = Execute<Blog>(context, "SELECT * FROM dbo.Blogs");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.