How do you minimize the performance hit when upgrading to EF 4.1 from LINQ to SQL?

随声附和 提交于 2019-12-03 17:15:54

Final note: I'm using a repository pattern as a mediator, and each usage of a repository is placed in a using block. For "get" operations, this results in entities becoming detached once I've obtained the data I need from the database.

Well this is not required...

  1. Entity Framework's default architecture already implements repository pattern.
  2. Keeping ObjectContext alive does not mean you are keeping your connection to database alive.
  3. Only when you are loading from or saving changes to database, a new connection from connection pool is grabbed and operation is performed.

Ofcourse, using block will slow down because each using block will do following,

  1. Initialize Context (requires loading metadata from resources)
  2. Validate few things
  3. Open connection to DB
  4. Perform your tasks
  5. Clean up and close DB

Now first two steps sure will take lot of time, and you will have multiple objects of same type living longer in your app because each new context will create a new copy of same object for every query.

Entity Framework already implements Identity Map, that means that it will keep the object alive and only one copy of object for same primary key throughout the lifetime of context, that will not only save memory but will also perform faster.

I would advise to not use Using blocks for every query or smaller steps but rather, you should keep your ObjectContext alive throughout lifetime of your application. And you do not need to implement caching or repository at all.

Read here and here about internal working of Entity framework. It is related to EFv4 and ObjectContext API but EFv4.1 with DbContext API is just wrapper around EFv4.

If you feel that your query is slow, try to execute it twice on the same context and twice on different instances of the context. The first test will check if the problem is in object materialization because objects will be materialized only for the first query and the second test will check if there is any problem with context initialization (this should not happen if you are using standard context creation with connection string).

It would be also interesting to compare execution with compiled query but I have a feeling that compiled queries are not part of DbContext API.

When you have changed to a Code First approach, has this changed the structure of the database?

My guess is yes and this is what is causing the change in performance.

I also noticed on thing in your class, you have:

public int TrialDefinitionId { get; set; }

and:

public virtual TrialDefinition TrialDefinition { get; set; }

Are both of these required?

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