c#.NET with Entity Framework 4 - how to handle context? best practices?
We are undergoing a migration from classic ASP with SQL and Sprocs. Our choice fell upon c#.net 4 Webforms with Entity Framework 4.
My question is how to handle the context. Example:
Calling repository function GetProductById()
, which open up a new context (using) and then we change something on the object and we save it.
When we save it we wont be in the same context as when we fetched the object.
The above didn't really work for us. We then tried to send the context around in our application. While this worked we didn't really want to work this way if开发者_如何学JAVA we didn't have to.
We are currently using a third option, storing the current context in a global variable. We dispose the context when we have saved it. However we're not sure if this is a viable way in the long run or if we're to hit a wall with this method.
We've tried to search for best practices on this topic but not really been able to find any. Would appreciate and help on this topic.
The Unit of Work pattern described in this article might help, although the examples in the article are with an MVC app rather than an WebForms one.
http://msdn.microsoft.com/en-us/ff714955.aspx
Use object keys
When you get an object from the DB and then manipulate it and after some time (after context has been discarded) want to save it back, use primary key values.
create a new instance of the correct entity object and set key properties (and those that have to be changes) and then save it against newly created context.
Or you can get it again before saving. It's a waste of resources but it is the most bullet proof way of doing it. Eve though I wouldn't recomend it.
Using ASP? Go with MVC then
I highly recomend you rather switch to Asp.net MVC if you're used to ASP, then you'll be better and easier at home in MVC.
Another option available to you is to have the context be put on the thread request. This is done by creating the context on the BeginRequest event of a HTTPModule. You then need to be sure you handle any resources you have created that need to be disposed of in the EndRequest event.
After getting a label on our way to work (Unit of work pattern) we found this link that is pretty much exactly how we work and it might be helpful for anyone with the same thoughts as we had:
http://dotnet.dzone.com/news/using-unit-work-pattern-entity?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+zones%2Fdotnet+%28.NET+Zone%29
精彩评论