如何在Entity Framework中将外键值设置为NULL。

huangapple go评论49阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年2月24日 06:46:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75551093.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定