Linq to Entities: add an object without saving changes

Suppose I have the following code:

TEModule teModule = Context.TEModules.Where(module => module.EnumValue.Equals(text.ModuleName)).FirstOrDefault(); if (teModule == null) { teModule = new TEModule(); teModule.EnumValue = text.ModuleName; Context.TEModules.AddObject(teModule); //Context.SaveChanges(); TEModule aux = Context.TEModules.Where(module => module.EnumValue.Equals(teModule.ModuleName)).FirstOrDefault(); } 

My problem is that if I save the SaveChanges comment, then the next time the aux object is always null, because Context.TEModules is empty even when I call AddObject . However, if I call SaveChanges after AddObject, then on the next request, the aux object will not be null. The problem is that I donโ€™t want to call SaveChanges so often, because this is not the only piece of code into which I add objects, and performance decreases if I do this.

So the question is: do I need to ramp SaveChanges after every call to AddObject, if later I need to know if this object exists?

+4
source share
1 answer

The goal of the linq-to-entity query must be executed and the execution is executed in the database, so if you have not saved the object, its database representation does not exist.

If you need to find locally stored objects (not yet saved), you must query ObjectStateManager .

 var entity = Context.ObjectStateManager.GetObjectStateEntries(EntitiState.Added) .Where(e => !e.IsRelationship) .Select(e => e.Entity) .OfType<TEModule>() .FirstOrDefault(m => m.EnumValue.Equals(teModule.ModuleName)); 
+4
source

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


All Articles