ASP.NET EntityFramework 4 data context best practice
I'm working on a project which is using EntityFramework 4 and I am using the entity objects as my business开发者_如何转开发 objects. I ran into an issue recently where I had a context declared in a using statement in a user control. The method the statement was in returned an entity object which got used in another control. So I had to detach the entity then attach it to the new context in the other control. I would like to avoid this if possible. What I'm thinking is I would like to declare a context in the master page and then pass that to any page/usercontrol that needs it so they are all using the same context and I don't have to write all these using statements.
My questions are these:
1) is it a bad practice to declare a context on Pre_Init/Page_Load and then dispose of it on Page_Unload?
2) if it is what is the best practice for handling them?
3) if I do go the route of declaring the context in the master page what is the best way to pass that to the pages/usercontrols?
The biggest issue is that you've coupled the EF context to your presentation layer. You're running into issues of separation of concerns here and it's manifesting itself as EF context confusion.
Without knowing anything about the specific of your application, the typical best practice would be to encapsulate your EF context beyond a repository pattern rather than exposing your context directly to the UI. Use the repository to get the entities that you need and pass the entities/model around. If you have a complex entity with parent/child relationships, eager load the child entities if you're using them anyway. Therefore, you can get everything you need in a single using statement.
If you want to post code, we can get into greater specifics. But to summarize:
- Don't put a context in ever user control
- Get the entire model at the top of your request and pass the appropriate entity to each user control (in this top level request will be your using statement dealing with the context)
精彩评论