开发者

Get TraceString for your business objects in the Entity Framework

开发者 https://www.devze.com 2023-01-21 09:05 出处:网络
How do I开发者_运维百科 get the trace string for a query like this: var product = _context.Products.Where( p => p.Category == \"Windows\" )

How do I开发者_运维百科 get the trace string for a query like this:

var product = _context.Products.Where( p => p.Category == "Windows" )
                               .SingleOrDefault();

// I can't do this since product is not an ObjectQuery instance
// product.ToTraceString();


Different answer for different problem.

You can't call ToTraceString() on this:

var product = _context.Products.Where( p => p.Category == "Windows" )
                               .SingleOrDefault();

You can do this:

var q = _context.Products.Where( p => p.Category == "Windows" )
var ts = ((ObjectQuery)q).ToTraceString();
var product = q.SingleOrDefault();

... but it's not 100% accurate. The MSSQL EF provider will use a TOP 2 for Single which this will miss.

You can come close with this:

var q = _context.Products.Where( p => p.Category == "Windows" )
var ts = ((ObjectQuery)q.Take(2)).ToTraceString();
var product = q.SingleOrDefault();

...which should get you the right SQL but requires knowledge of the implementation.

Original question misrepresented the problem. My original answer was:

var ts = (product as ObjectQuery).ToTraceString();


This is what you need to do:

string trace = ((ObjectQuery)_context.Products
                           .Where(p => p.Category == "Windows")).ToTraceString();

Compiler will not accept a cast from Product EntityObject to ObjectQuery but IQueryable<Product> is castable to ObjectQuery, so basically you just need to get rid of that .SingleOrDefault() method before trying to see the trace string.

0

精彩评论

暂无评论...
验证码 换一张
取 消