c# - Entity Framework Core 导航属性不会保持为空

标签 c# entity-framework entity-framework-core

我有一个带有链接类的类,例如想象一个人和一条狗。它在 PersonDto 中是这样映射的:

public int? DogId { get; set; }
public virtual DogDto Dog { get; set; }

对于许多人来说,DogId 为空,但在我更改 Person 中的某些内容并执行 SaveChanges 之后, Entity Framework 坚持认为它应该插入一个空白条目。

我的场景要大得多但简化后看起来像这样:

var person = await _entities.Persons.Where(p => p.Name == "Ann")
            .Select(p => p).Include(p => p.Dog).First();
person.Name = "Bob";
_entities.SaveChanges();

假设现在 Ann 没有狗,DogId 应该保持为空。

SQL Entity Framework Core 执行如下 INSERT:

DECLARE @inserted0 TABLE ([Id] int, [_Position] [int]);
MERGE [Dogs] USING (
VALUES (@p0, @p1, @p2, @p3, @p4, 0),
(@p5, @p6, @p7, @p8, @p9, 1)) AS i ([Col1], [Col2], [Col3], [Col4], [Col5], 
_Position) ON 1=0
WHEN NOT MATCHED THEN
INSERT ([Col1], [Col2], [Col3], [Col4], [Col5])
VALUES (i.[Col1], i.[Col2], i.[Col3], i.[Col4], i.[Col5])
OUTPUT INSERTED.[Id], i._Position
INTO @inserted0;

我错过了什么。不会int?足以让它为空?

最佳答案

我只是想发布一个答案,以防任何搜索到此为止。

虚拟无关紧要是完全正确的,问题出在我的 Dto 和域层之间的某些映射中,我在其中错误地附加了一个空白条目。

关于c# - Entity Framework Core 导航属性不会保持为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52332546/

相关文章:

c# - 即使在检查 null 后字典也会抛出异常

c# - 合并两个 linq 表达式

c# - 在 Entity Framework Core 2.0 中执行存储过程

.net - Project.json 工具现在应该去哪里?

c# - Controller 上的多个路由

c# - 如何在 DataGridView 的底部绘制行?

c# - 如何让 Chutzpah 发现 Typescript 文件?

c# - Entity Framework 多对象上下文

entity-framework - EF Core 2.0枚举存储为字符串

c# - 使用 Autofac 和 EF Core 3.1 的内存泄漏(从 2.2 迁移后)