简体   繁体   English

查询以包含挂起的插入

[英]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. 我正在使用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. 我希望foos既包括数据库中的记录,也包括挂起插入的记录。 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. 在我的实际代码中,我将在运行查询之前插入/更新多个Foos。

Edit 编辑

I'm looking for something that has a similar behavior to Find . 我正在寻找与Find有类似行为的东西。 Find will check the context first, then goes to the database if nothing is found. Find将首先检查上下文,然后在没有找到任何内容的情况下转到数据库。 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();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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