从 Where 表达式获取 SQL 查询

Get SQL query from Where expression

我有一个使用 EF6 上下文的 .Net Framework 控制台应用程序,我从中选择使用 mehdime 实体范围,并且我试图在我的程序中获得结果 SQL 查询。

我想获得生成的 SQL,它会从 WHERE 产生,但似乎找不到如何实现它(我的 google-fu 很弱,我'我可能问错了问题)。

代码:

list<int> mailIds = new List<int>(); //list of ids that might be in db
using(var dbScope = Contexts.Scope.Create())
{
   var emails = Contexts.Mail.ResponseMail.Where(m => mailIds.Contains(m.Id));
   //I'd like to get the query resulting from this WHERE in a text format so that I can save it somewhere
   .....
}

Contexts.cs class:

using Mehdime.Entity;

....

class Contexts
{
    public static IDbContextScopeFactory Scope { get; } = new DbContextScopeFactory();
    private static IAmbientDbContextLocator Locator { get; } = new AmbientDbContextLocator();

    public static MailContext Mail => Locator.Get<MailContext>();
    ....
}

和MailCotext.cs:

public class MailContext : DbContext
{
    public MailContext() : base(nameof(MailContext)) 
    {
        Database.SetInitializer(new CreateDatabaseAndSyncEnums<MailContext>());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }

    public DbSet<ResponseMessages> ResponseMail { get; set; }
}

您可以使用 ff:

从 EF 获取生成的查询
var emails = Contexts.Mail.ResponseMail.Where(m => mailIds.Contains(m.Id));
// using the IQueryable extract the query
var sql = ((System.Data.Entity.Core.Objects.ObjectQuery)emails)
            .ToTraceString();

您可以为此创建一个扩展,这样您就可以轻松获得从 IQueryables 生成的查询。