英文:
How to make a foreign key value NULL in Entity Framework
问题
class Table1
{
int Id;
int Var1;
Table2? table2;
}
class Table2
{
int Id;
//Other fields
}
Table1
指的是 Table2
。由于在 Table1
类中,Table2
字段是可空的,为什么我不能以以下方式将其设置为 null?
var zeroVars = table1.where(i => i.Var1 == 0).ToList();
foreach (var t2 in zeroVars)
{
t2.Var1 = -1; // 可行
t2.table2 = null; // 不会改变。不会报错
}
英文:
class Table1
{
int Id;
int Var1;
Table2? table2;
}
class Table2
{
int Id;
//Other fields
}
Table1
refers to Table2
. Since Table2
field is nullable in class Table1
, why can't I set it to null the following way?
var zeroVars = table1.where(i => i.Var1 == 0).ToList();
foreach (var t2 in zeroVars)
{
t2.Var1= -1; // Works
t2.table2 = null; // Does not change. No error
}
答案1
得分: 2
问题在于您没有急切加载Table2以便更改跟踪知道您要删除它。这应该按预期工作:
var zeroVars = table1
.Include(i => i.table2)
.Where(i => i.Var1 == 0)
.ToList();
foreach (var t2 in zeroVars)
{
t2.Var1 = -1;
t2.table2 = null;
}
如果您不加载引用,那么在尝试设置它之前,该值实际上为null,除非它在尝试设置之前进行了急切加载或延迟加载。
英文:
The issue is that you haven't eager loaded Table2 for the change tracking to know that you want to remove it. This should work as expected:
var zeroVars = table1
.Include(i => i.table2)
.Where(i => i.Var1 == 0)
.ToList();
foreach(var t2 in zeroVars)
{
t2.Var1= -1;
t2.table2 = null;
}
If you don't load the reference then the value is effectively null to begin with, unless it is eager or lazy loaded before attempting to set it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论