我怎样才能编写一个包含挂起的插入以及数据库中的记录的查询?我正在使用 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();
关于c# - 查询以包含挂起的插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9318137/