What is the overhead of Entity Framework tracking?

时光毁灭记忆、已成空白 提交于 2021-01-27 11:50:51

问题


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; }

rather than

IQueryable<MyPoco> MyThings { get; }

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

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

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.

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?


回答1:


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 page on Stages of Query Execution details the cost associated with each step of query execution.

Edit:

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.




回答2:


Navigation properties in the model classes as declared as virtual so as to imply lazy load feature which means the navigation property will only be needed if required. As far as the Entity objects are concerned, there main aim is to load the specific table records from the database into the DbSet which comes from DbContext. You can't use IQueryable in this case. Also, it doesn't make any sense with the DataContext. IQueryable is an altogether different interface



来源:https://stackoverflow.com/questions/8257523/what-is-the-overhead-of-entity-framework-tracking

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