0

Say I have a LINQ query:

var query = (from person in ctx.People where person.Name == "John" select person);

ctx is a context inheriting from System.Data.Entity.DbContext.

Now how do I get the full SQL query including the parameters? I have tried:

var sql = ((ObjectQuery) query).ToTraceString();
sql = query.String();
context.Database.Log = (s) => sql += s;

The first solution throws an invalid cast exception. The second solution gives me only the query part which references variables that are not included. The third prints the "variables" in a strange format.

user1151923
  • 1,853
  • 6
  • 28
  • 44
  • 1
    Did you tried LINQPad ? http://www.linqpad.net/ – Kamlesh Arya Nov 11 '14 at 11:26
  • is the query correct copy/pasted or just typed? "where person.Name = "John" " is doing an assignment instead of an equality test. – user1666620 Nov 11 '14 at 11:42
  • 1
    @user1666620 Just a random typed query, fixed that error now – user1151923 Nov 11 '14 at 11:47
  • @user1151923 Which version of EF are you using? The method varies... e.g. ToTraceString will not work as simply as you are using it if you are using EF6 – Paul Zahra Nov 11 '14 at 16:59
  • possible duplicate of [How do I view the SQL generated by the entity framework?](http://stackoverflow.com/questions/1412863/how-do-i-view-the-sql-generated-by-the-entity-framework) – Paul Zahra Nov 11 '14 at 17:00

1 Answers1

0

var query = from person in ctx.People where person.Name == "John" select person; string Sql = ctx.GetCommand(query).CommandText;

mss
  • 64
  • 3