Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to include pending inserts

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.

like image 328
cadrell0 Avatar asked Dec 29 '25 11:12

cadrell0


2 Answers

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();
like image 123
Ladislav Mrnka Avatar answered Jan 01 '26 03:01

Ladislav Mrnka


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.

like image 38
zmbq Avatar answered Jan 01 '26 03:01

zmbq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!