MVC and Entity Framework when deleting Entity objects

When do you place context objects Object objects in an entity structure and MVC?

For example, if I have a face table and I select an entry in the controller method, delete it and pass it back to my view, then the record will not be used in the view.

Do I have to get rid of it somehow after processing my view? or not to dispose of it at all?

+6
source share
3 answers

One option is to create it in the Global.asax begin request event and delete it in the Global.asax completion event. Each page simply uses this one (stored and retrieved in HttpContext.Current.Items or in the local thread store) without deleting it. This allows it to be available for your viewing in order to do lazy loading, but still disposes of it after the request is completed.

Another option is to make sure that everything you need is already loaded before calling your view (via .First (),. ToList () and .Include (property) to include data on navigation properties) and get rid of it immediately. Both methods work.

+1
source

I assume that you are talking about disposing of the Entity Framework "Contexts" because the objects themselves are not disposable.

We found that it is best to leave objects in our data layer and map them to POCOs / DTO, which contain all the necessary information for this view. This way, we are not trying to lazily load data while we do our presentation. We transfer the data access code to using(var context = contextFactory.Get()) , so that the context will be automatically deleted before the method ends, but after we load all the data that we extract into the collection in memory.

0
source

Let's look at a typical user usage pattern, you will never open one element and you will not leave, in fact we move again and again between elements, browse and browse elements, change and save them.

If you save an ObjectContext throughout the session, you will use a little more memory for each user, but you will reduce your application to the database transfer and you will be able to accumulate changes. And save the changes immediately. Since EF implements an Identity Pattern, you will not load multiple copies of the same object.

Otherwise, if you remove the ObjectContext, reduce the memory, but increase the overhead of loading the objects again and again. You can load multiple copies of the same object over and over views and increase the loading of queries on the database server.

0
source

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


All Articles