ASP.NET requests ... what to do with Linq DataContext?

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

Therefore, I use datacontext Linq to SQL to track and store entities in an ASP.NET web application. This intranet app does not have tons of users at a time. Right now I cam keep the datacontext in session state, which makes me feel dirty! I seem to need a context that is always present because I need to keep track of changes for objects that are changing. All of our screens have a Save button, which then calls the SubmitChanges () method in the DataContext and stores all pending changes in memory.

Should I store a DataContext? Should I get rid of it at the end of each request, and then somehow recreate it and get the pending changes? If I have to recreate it every time, I don’t understand how the context could know what changed without a ton of redundant database hits on each request.

+4
source share
2 answers

Firstly, I would say not to put things in the Session at all. Especially if you have few users, just download the data when you need it.

Do not store the data context at all. Just create a new one on every page when you need it. When they click the "Save" button, re-create the data context, load the object from the database, make the necessary changes based on the form input and save it back to the database. It should be only two database accesses for each object, one for loading, and then one for saving it.

+4
source

I believe the best practice in the data context is the Unit of Work template, where the unit of work volume is the only request that you serve. Create a new data context every time you need to make changes. If you are worried about overwriting the changes that were made after drawing the previous page, consider using and saving the date / time in a hidden field and checking that it matches the return from the data context when receiving the object for updating.

+3
source

Source: https://habr.com/ru/post/1303267/


All Articles