c# - 查询以包含挂起的插入

标签 c# entity-framework

我怎样才能编写一个包含挂起的插入以及数据库中的记录的查询?我正在使用 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/

相关文章:

c# - 如何在不冒应用程序失败风险的情况下调用 SemaphoreSlim.Release()?

c# - 要序列化的同名属性

entity-framework - 为什么在 Entity Framework 6中仍未实现ON DELETE SET NULL?有障碍吗?

sql - 在本地运行 Azure 移动服务器项目

c# - 如何在 Entity Framework 和 Mysql 中使用规范函数

c# - log4net 不在单独的文件中记录错误和 fatal error

c# - 数据库连接C#

c# - SQL > Linq to Sql,SQL 查询有效,Linq to SQL 返回空数据集

.Net Entity Framework & POCO ...查询全表问题

c# - 如何防止winforms设计器将Text属性设置为实例名称