从Where表达式获取SQL查询

问题描述 投票:0回答:1

我有一个使用EF6上下文的.Net框架控制台应用程序,我使用mehdime实体范围进行选择,我试图在我的程序中得到生成的SQL查询。

我想得到生成的SQL,将从WHERE的结果,但似乎不能找到如何实现(我的google-fu是弱,我proabbly问的问题是错误的)。

代码是这样的。

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类

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; }
}
c# linq-to-sql entity-framework-6 mehdime-entity
1个回答
2
投票

你可以使用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中获得生成的查询。

© www.soinside.com 2019 - 2024. All rights reserved.