开发者

ASP.NET Requests... what do to with a Linq DataContext?

开发者 https://www.devze.com 2022-12-22 13:41 出处:网络
Sorry, if this is a duplicate. Please point me to the appropriate question if this is but I could not find exactly what I am looking for.

Sorry, if this is a duplicate. Please point me to the appropriate question if this is but I could not find exactly what I am looking for.

So I am using a Linq to SQL datacontext for entity tracking and persistence in an ASP.NET web application. It is for an Intranet application that does not have a ton of users at a time. Right now I cam storing the datacontext in session state, which makes me feel dirty! It seems like I need the context always to be present though because I need to preserve the change tracking on the entities that are being modified. All of our screens have a Save button that would then call SubmitChanges() on the DataContext and persist all of the pending changes in memory.

Should I be storing the DataContext? Should I be disposing of it at the end of each request and then recreate it somehow and get the pending changes? If I should recreate it every time, I dont understand how the context could know what has changed without a开发者_JAVA技巧 ton of redundant database hits on each request.


First, I would say to stop putting things in Session altogether. Especially if you don't have a lot of users, just load the data when you need it.

Don't store the data context at all. Just create a new one on each page when you need it. When they hit the Save button, recreate a data context, load the object from the database, make the changes necessary based on the form input, and then save it back to the database. It should just be two database hits for each object, one to load, and then one to save it back.


I think the best practice with the data context is the Unit of Work pattern, where the scope of the Unit of Work is the single request that you are servicing. Instantiate a new data context each time you need to make changes. If you're concerned about overwriting changes that have been made after drawing the previous page, then consider using and persisting a version/timestamp in a hidden field and checking it against that returned from the data context when retrieving the entity to update.

0

精彩评论

暂无评论...
验证码 换一张
取 消