繁体   English   中英

查询以包含挂起的插入

[英]Query to include pending inserts

如何编写包含挂起插入的查询以及数据库中的记录? 我正在使用EF 4.3 Code First。

防爆。

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

我希望foos既包括数据库中的记录,也包括挂起插入的记录。 我只获取数据库中的值。

在我的实际代码中,我将在运行查询之前插入/更新多个Foos。

编辑

我正在寻找与Find有类似行为的东西。 Find将首先检查上下文,然后在没有找到任何内容的情况下转到数据库。 我想结合上下文和数据库的结果。

试试这个:

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

或者更改操作顺序的更好选择:

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