Is it possible to force the Entity Framework to recognize objects that have been created and have not yet been saved to the database?

Say Table1 - a table with two columns. Table 1ID and name.

If I do the following code ...

var Obj1 = new Table1(); Obj1.Name = "hello" TestDBEntities.AddToTable1(Obj1); var currObj = Table1.Where(o => o.Name.Contains("hello")).FirstOrDefault(); 

currObj will return null.

But if I do it

 var Obj1 = new Table1(); Obj1.Name = "hello" TestDBEntities.AddToTable1(Obj1); **TestDBEntitles.SaveChanges();** var currObj = Table1.Where(o => o.Name.Contains("hello")).FirstOrDefault(); 

Then currObj will return the first object I created. This is because this object is in the database.

I am creating a large batch process and I do not want to keep everything in the database until the end. However, I have to do checks, such as making sure that a certain object has not yet been added, etc., which require me to reference these objects before they are stored in the database.

Is it possible to make LINQ queries in the Entity Framework that can be aware of objects that are in memory that were not stored in the database.

+4
source share
3 answers

Add the created and unsaved objects to the List<T> , then filter this list with linq, as you did above.

EDIT: Actually, I'm standing fixed. It looks like you can specify merge options on an ObjectContext .

 TestDBEntities.ObjectStateManager.GetObjectStateEntries(EntityState.Added) .Where(o => o.GetType() == typeof(Object1Type) && o => o.Name.Contains("hello")) .FirstOrDefault(); 

docs .

+3
source

I'm a little late here ... @DavidWicks answer doesn't tell the whole story!

Context provides a request mechanism - and it is much easier in EF4.1 than 4.0

In 4.1, take a look at http://msdn.microsoft.com/en-us/library/gg696248(v=vs.103).aspx the dbSet.Local property contains all local changes for objects (which have not been deleted) in context, therefore request for it is all you need!

+6
source

This is just what you need to do:

  Datacontext.YourTable.Add(entity); var x=Datacontext.YourTable.Local; 

With .Local get local state of dbset object :)

0
source

All Articles