我在应用程序中有一个可选的独立关联外键,这里是数据库上下文和实体的简化版本。
背景
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/