在EF Core 2.1中的DbContext上执行RAW SQL [英] Execute RAW SQL on DbContext in EF Core 2.1

查看:360
本文介绍了在EF Core 2.1中的DbContext上执行RAW SQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对此进行了研究并始终找到这样的示例:

  var blogs = context.Blogs 
.FromSql( SELECT * FROM dbo.Blogs)
.ToList();

问题是,我不想在Blogs表上运行原始SQL。基本上,我想实现这样的接口:

  bool ExecuteNonSafeSql(
string connectionString,
string sql);

是否可以使用DbContext做到这一点?

安全性返回 SQL命令。



仅实体类型和 FromSql 支持 noreferrer>查询类型



因此,最接近的解决方案是定义查询类型(保存查询结果的类)并使用 FromSql ,但是它不是通用的-查询类型必须通过fluent API在 DbContext 中注册,并且该方法应接收指定该类型的通用参数,例如

 类ResultType 
{
// ...
}

然后

  modelBuilder.Query< ResultType>(); 

最后

  db.Query< ResultType>()。FromSql(...)

注意 Database.ExecuteSqlCommand 可以执行任意SQL,但不能用于返回序列( IEnumerable< T> IQueryable< T> )。


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. Basically, I want to implement an interface like this:

bool ExecuteNonSafeSql(
    string connectionString,
    string sql);

Is there a way to do that with DbContext?

解决方案

At the time of writing (EF Core 2.1), there is no way to execute arbitrary secuence returning SQL command.

Only entity types and Query Types are supported via 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, e.g

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>).

这篇关于在EF Core 2.1中的DbContext上执行RAW SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆