How can I write a query that will include pending inserts as well are records in the database? I am using EF 4.3 Code First.
Ex.
Foo = new Foo { Bar = 5 };
dbContext.Set<Foo>.Add(foo);
IEnumerable<Foo> foos = dbContext.Set<Foo>.Where(f => f.Bar == 5).ToList();
ActOnFoos(foos);
dbContext.SaveChanges();
I want foos to include both the records in the database as well as the records that are pending insert. I am only getting the values that are in the database.
In my actual code I'll have multiple Foos that are being inserted / updated before I run my query.
Edit
I'm looking for something that has a similar behavior to Find. Find will check the context first, then goes to the database if nothing is found. I want to combine results from the context and the database.
Try this:
DbSet<Foo> set = dbContext.Set<Foo>();
Foo = new Foo { Bar = 5 };
set.Add(foo);
IEnumerable<Foo> foos = set.Local
.Where(f => f.Bar == 5)
.Union(set.Where(f => f.Bar == 5)
.AsEnumerable());
ActOnFoos(foos);
dbContext.SaveChanges();
Or the better option with changing order of operations:
DbSet<Foo> set = dbContext.Set<Foo>();
var data = set.Where(f => f.Bar == 5).AsEnumerable());
Foo = new Foo { Bar = 5 };
set.Add(foo);
IEnumerable<Foo> foos = set.Local.Where(f => f.Bar == 5);
ActOnFoos(foos);
dbContext.SaveChanges();
I think it would be better to actually insert the records within a transaction, and rollback if you decide you don't want to insert them after all.
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