EF Core 不会将可空字段的值设置为 NULL
EF Core will not set value of nullable field to NULL
我有一个实体,它有一个可为 null 的 int,它是自身的一对一外键。简化一下,就是这个实体:
public class Step
{
public int StepId { get; set; }
public string Foo { get; set; }
public int? RelatedStepId { get; set; }
[ForeignKey("RelatedStepId")]
public Step RelatedStep { get; set; }
}
这工作正常 - 我能够将 RelatedStepId
设置为另一条记录的 StepId
的值。但是,有时我需要打破这种关系。如果我将 RelatedStepId
设置为 null
然后保存更改,该字段将保留其先前的值。我已经验证 RelatedStepId
确实是 null
,但是当我记录正在生成的 SQL 时(使用 .EnableSensitiveDataLogging() 所以我可以看到值)我可以看到它正在通过SQL 中的先前值,而不是 null
.
我觉得我一定遗漏了一些简单的东西,但我一直在搜索和搜索,到目前为止我还没有找到与这个特定问题相关的任何内容。如何让 EF Core 实际发送 null
作为 RelatedStepId
的值?
您也应该将 RelatedStep
设置为 null。我猜你没有清除这个对象。
填RelatedStepId
或RelatedStep
其中之一就足以让EF
保存值,如果你不想,则必须将它们都清除。
我有一个实体,它有一个可为 null 的 int,它是自身的一对一外键。简化一下,就是这个实体:
public class Step
{
public int StepId { get; set; }
public string Foo { get; set; }
public int? RelatedStepId { get; set; }
[ForeignKey("RelatedStepId")]
public Step RelatedStep { get; set; }
}
这工作正常 - 我能够将 RelatedStepId
设置为另一条记录的 StepId
的值。但是,有时我需要打破这种关系。如果我将 RelatedStepId
设置为 null
然后保存更改,该字段将保留其先前的值。我已经验证 RelatedStepId
确实是 null
,但是当我记录正在生成的 SQL 时(使用 .EnableSensitiveDataLogging() 所以我可以看到值)我可以看到它正在通过SQL 中的先前值,而不是 null
.
我觉得我一定遗漏了一些简单的东西,但我一直在搜索和搜索,到目前为止我还没有找到与这个特定问题相关的任何内容。如何让 EF Core 实际发送 null
作为 RelatedStepId
的值?
您也应该将 RelatedStep
设置为 null。我猜你没有清除这个对象。
填RelatedStepId
或RelatedStep
其中之一就足以让EF
保存值,如果你不想,则必须将它们都清除。