Get TraceString for your business objects in the Entity Framework

☆樱花仙子☆ 提交于 2020-01-07 04:44:28

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/3980874/get-tracestring-for-your-business-objects-in-the-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!