0

I have .Net Framework console application using EF6 context from which I'm selecting using mehdime entity scope and I'm trying to get the resulting SQL query in my program.

I'd like to get the generated SQL that would result from the WHERE, but can't seem to find how to achieve that (my google-fu is weak and I'm proabbly asking the question wrong).

The code:

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

The 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>();
    ....
}

And the 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; }
}
mishan
  • 1,177
  • 3
  • 19
  • 42

1 Answers1

2

You can get the generated query from EF using the ff:

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();

You could create an extension for this so that it would be easy for you to get the queries generated from IQueryables.

jegtugado
  • 5,081
  • 1
  • 12
  • 35
  • Thanks, that's what I was looking for and missing. :) I knew it was somehow like that but did not remmber how. – mishan Jun 11 '20 at 11:47