简体   繁体   中英

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.

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();

我认为最好在事务中插入记录,如果你决定不想插入它们就回滚。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM