实体框架跟踪的开销是多少? [英] What is the overhead of Entity Framework tracking?

查看:55
本文介绍了实体框架跟踪的开销是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚与一位同事讨论了Entity Framework更改跟踪.我们最终发现我的上下文界面应该具有

I've just been talking with a colleague about Entity Framework change tracking. We eventually figured out that my context interface should have

IDBSet<MyPoco> MyThings { get; }

而不是

IQueryable<MyPoco> MyThings { get; }

,并且我的POCO还应具有 virtual 的所有属性.

and that my POCO should also have all it's properties as virtual.

使用调试器,我们可以看到跟踪对象,并且结果包含我实际POCO的代理.

Using the debugger we could then see the tracking objects and also that the results contained proxies to my actual POCOs.

如果我没有作为 virtual 的POCO属性,并且使用 IQueryable<> 而不是 IDbSet<> 的上下文界面>我什么都没得到.

If I don't have my POCO properties as virtual and have my context interface using IQueryable<> instead of IDbSet<> I don't get any of that.

在这种情况下,我仅查询数据库,但将来会希望通过Entity Framework更新数据库.

In this instance I am only querying the database, but in the future will want to update the database via Entity Framework.

因此,为了将来使我的生活变得更轻松,当我将这段代码作为参考时,如果我永远不会使用跟踪信息/代理,是否会对性能造成不利影响?

So, to make my life easier in the future when I come to look at this code as a reference, is there any performance penalty in having the tracking info/proxies there when I will never make use of them?

推荐答案

在EF中添加实体会降低性能.使用实体框架查询时,EF会保留从数据库加载的值的副本.同样,单个Context实例仅跟踪实体的单个实例.因此,EF必须在创建实例之前检查它是否已经有该实体的副本(即,幕后会有很多比较).

There is a performance penalty of tacking entities in EF. When you query using entity framework EF will keep a copy of values loaded from database. Also single Context instance keeps track of only single instance of an entity. So EF has to check whether it already has a copy of the entity before it creates an instance(ie. There will be lot of comparisons going behind the scenes).

因此,如果不需要它,请避免使用它.您可以按照以下步骤进行操作.

So avoid it if you don't need it. You can do so as follows.

IQueryable<MyPoco> MyThings { get { return db.MyThings.AsNoTracking(); } }

位于查询执行阶段上的MSDN页面详细介绍了与查询执行的每个步骤.

MSDN page on Stages of Query Execution details the cost associated with each step of query execution.

您不应公开 IDBSet< MyPoco>MyThings ,因为它告诉您的API使用者,实际上您打算查询数据时可以添加,更新和删除实体.

You should not expose IDBSet<MyPoco> MyThings because that tells the consumer of your API that your entities can be added, updated and deleted when in fact you intend to query the data.

这篇关于实体框架跟踪的开销是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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