Say Table1 is a table with two columns. Table1ID 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 this
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 that object is in the database.
I'm creating a large batch process and I don't want to save everything to the database until the end. However, I have to do checks like make sure a certain object hasn't already been added etc. which require me to reference these objects before they have been saved to the database.
Is it possible to make LINQ queries in Entity Framework that can be aware of objects that are in memory which have not been saved to database.
I'm a bit late here... @DavidWicks answer doesn't tell the whole story!
The context does provide a mechanism to query - and it got a lot 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 holds all of the local changes for objects (that have not been deleted) in the context, so querying against that is all you need!
Add the created and unsaved objects to a List<T>
then filter that list with linq like you did above.
EDIT: actually, i stand corrected. It looks like you can specify merge options on the ObjectContext
.
TestDBEntities.ObjectStateManager.GetObjectStateEntries(EntityState.Added)
.Where(o => o.GetType() == typeof(Object1Type)
&& o => o.Name.Contains("hello"))
.FirstOrDefault();
the docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With