c# - 无法使用独立关联将可选外键设置为空

标签 c# entity-framework entity-framework-6

我在应用程序中有一个可选的独立关联外键,这里是数据库上下文和实体的简化版本。

背景

public class AppContext : DbContext
{
    public DbSet<Foo> Foos { get; set; }
    public DbSet<Bar> Bars { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Bar>().HasOptional(b => b.Foo);
    }
}

实体

public class Foo
{
    public int Id { get; set; }
    public virtual ICollection<Bar> Bars { get; set; }
}
public class Bar
{
    public int Id { get; set; }
    public virtual Foo Foo { get; set; }
}

上下文和实体位于不同的程序集中,我无法更改实体,因为它是一个子存储库,将被其他项目使用。

问题

当我想通过将其设置为空来删除外键时,它不会改变。

using (var db = new AppContext())
{
    var bar = db.Bars.Find(1);
    bar.Foo = null;
    db.SaveChanges();
}

这行得通

bar.Foo.Bars.Remove(bar);

但在我的情况下,这不是解决方案,所有柱状图都将加载到内存中,我不想进行不必要的数据库往返。

为什么以及如何解决这个问题?

最佳答案

我设法通过将它分配给未使用的变量来解决它。

var bar = db.Bars.Find(1);
var foo = bar.Foo;
bar.Foo = null;
db.SaveChanges();

PS:分配 null 两次或更多次不起作用。

bar.Foo = null;
bar.Foo = null;

关于c# - 无法使用独立关联将可选外键设置为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25321286/

相关文章:

c# - Entity Framework 6 中的所有查询是否都已编译?

c# - Entity Framework 6.0 代码优先 - 按主键过滤时在简单查询中获取重复项

c# - Entity Framework 无法使用二进制数组添加迁移

c# - 什么可能导致(托管)UIAutomation 在枚举子级时获得 self 引用

c# - DateTime 列可为空时 Entity Framework 种子方法 DateTime 错误

c# - .NET 标准的 System.Data.SqlClient 出错

asp.net - 使用 Jet 引擎使用 Entity Framework (代码优先)重命名列(并保留数据)

c# - 在 Visual Studio 开发服务器上启用 Soap Web 服务的 CORS 设置

c# - 为什么我的 COM 对象不显示组件服务中的方法?

c# - MongoDB C# 驱动程序 - 忽略绑定(bind)字段