调试实体框架SQL语句 [英] Debugging Entity Framework SQL statements

查看:153
本文介绍了调试实体框架SQL语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是来自我的网页主机 - http://i55.tinypic.com/263uiag.png



这是从我的本地服务器 - http://i53.tinypic.com/102t4xe.png



这是我担心的响应时间的增加。
我已经将问题缩小到代码
中的一行单位Nop.Data> EfRepository.cs> public void Insert(T entity)> _entities.Add(entity);
是的,我知道这是非常具体的NopCommerce,但关键是我正在寻找帮助如何调试这个。



有没有一些事件我可以捕获显示正在执行的SQL?
或者还有什么其他的事情可以在上述命令中了解更多实体框架中实际发生的事情。

解决方案

对于调试EF查询,最简单的方法是将查询转换为ObjectQuery并使用ToTraceString:

  var query = myContext .MyTable 
.Where(r => r.Id == searchId)
.Select(r => r);

Console.WriteLine(((ObjectQuery)查询).ToTraceString());

这将显示查询的底层SQL,您可以手动运行查询来调试为什么很慢以下是MSDN链接:



http://msdn.microsoft.com/en-us/library/system.data.objects.objectquery.totracestring.aspx



如果您尝试获取在上下文中调用SaveChanges()时运行的SQL,那不是那么容易。你可以看看EFTracingProvider:



http://blogs.msdn.com/b/jkowalski/archive/2009/06/ 11 / tracing-and-caching-in-entity-framework-available-on-msdn-code-gallery.aspx



或者,假设您使用SQL服务器,您可以直接访问SQL Profiler并捕获T-SQL语句(这是我的首选方法)。


I am having a weird pattern of response time when using the Entity Framework for SQL communication.

This is from my web host - http://i55.tinypic.com/263uiag.png

This is from my local server - http://i53.tinypic.com/102t4xe.png

It's the increase in response time I am worried about. I have narrowed the problem down to one single line in code Nop.Data > EfRepository.cs > public void Insert(T entity) > _entities.Add(entity); Yes I know this very specific for the NopCommerce, but the point is really that I am looking her for help on how to debug this.

Are there some events I can catch that display the SQL being executed? Or what other things can I do to find out more what is actually happening in the Entity Framework in that above command.

解决方案

For debugging EF queries, the easiest thing is to cast the query to ObjectQuery and use ToTraceString:

var query = myContext.MyTable
    .Where(r => r.Id == searchId)
    .Select(r => r);

Console.WriteLine(((ObjectQuery)query).ToTraceString());

This will show the underlying SQL for the query, and you can run the queries manually to debug why they are slow. Here is the MSDN link:

http://msdn.microsoft.com/en-us/library/system.data.objects.objectquery.totracestring.aspx

If you're trying to get the SQL which is run when you call SaveChanges() on your context, it's not as easy. You could take a look at EFTracingProvider:

http://blogs.msdn.com/b/jkowalski/archive/2009/06/11/tracing-and-caching-in-entity-framework-available-on-msdn-code-gallery.aspx

Or, assuming you use SQL Server, you can go directly to SQL Profiler and capture the T-SQL statements (this is my preferred approach).

这篇关于调试实体框架SQL语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆