c# - EF核心: No backing field could be found for property of entity type and the property does not have a getter

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

我在 EF Core 中遇到以下错误:找不到实体类型“Child”的属性“ParentId”的支持字段,并且该属性没有 getter。

这是我对子实体的配置:

            // create shadow property for Parent
            builder.Property<int>("ParentId").IsRequired();

            // make shadow property and foreign key the PK as well
            // i know this may not make the most sense here 
            // in this scenario but it's what I want to do.
            builder.HasKey("ParentId");

            // configure FK
            builder.HasOne(o => o.Parent)
                .WithOne()
                .HasForeignKey<Child>("ParentId");

还有我的实体:

public class Parent
{
    public int Id { get; set; }
}

public class Child 
{
    public Parent Parent { get; private set; }

    public void SetParent(Parent p) => Parent = p;
}

调用 dbContext.Children.Contains(myChild) 时出现错误:

var child = new Child();
child.Parent = new Parent();

dbContext.Children.Add(child);
dbContext.SaveChanges();

// works fine
Assert.True(dbContext.Children.Any());

// throws InvalidOperationException
Assert.True(dbContext.Children.Contains(myChild)):

如果我将阴影属性作为真实属性添加到模型中,如下所示:

public class Child 
{
    public int ParentId { get; set;} 

    public Parent Parent { get; private set; }

    public void SetParent(Parent p) => Parent = p;
}

然后一切正常。但如果可能的话,我想将其保留为影子属性。

最佳答案

更新:

刚刚检查了3天前发布的EF Core 3.1.7,异常消失了,这意味着它已经被报告/识别并修复。因此,您只需升级到该版本即可。

原文:

shadow属性的配置没问题。不幸的是,您遇到了 EF Core 3.x 错误之一。

为了将 Contains 方法转换为 SQL,EF Core 必须将其转换为 PK 相等比较,类似于(伪代码)

dbContext.Children.Any(c => PK(c) == PK(myChild))

从异常堆栈跟踪中可以看出,当 PK 是影子属性时,显然无法做到这一点。

我检查了此时最新的 EF 5 预览版,它似乎已修复(问题已消失)。因此,在它发布之前,解决方法是替换隐式实体相等比较(例如 Contains(entity)Equals(entity)==实体 等)与相应的显式 PK 比较。

在这种情况下,而不是

dbContext.Children.Contains(child)

您可以使用其中之一

dbContext.Children.Any(c => c.Parent.Id == child.Parent.Id)

(由于另一个 v3.x 缺陷导致 SQL 翻译更差)

dbContext.Children.Any(c => EF.Property<int>(c, "ParentId") == child.Parent.Id)

(与 v5.0 中一样的正确 SQL 翻译,但使用“魔术”字符串并需要显式指定影子属性名称和类型)

关于c# - EF核心: No backing field could be found for property of entity type and the property does not have a getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63391678/

相关文章:

azure - 在使用 GitHub 部署的 azure for dotnet core 站点上运行迁移

C# 控制台应用程序错误 - 无法识别/正确评估返回的 int

c# - Entity Framework 命名空间 - 上下文命名空间

c# - Entity Framework 迁移 - 未迁移的列

c# - 何时在 DbContext 构造函数中提供 DbContextOptions 与 OnConfiguring?

c# - EF Core 3.0 SumAsync 触发聚合函数异常

用于动态属性的 C# json 对象

c# - 无法从传输连接读取数据?

c# - 在 VS 2010 的 Winforms 项目中添加 WPF 窗口

c# - EntityFramework where 子句是否始终按相同顺序返回对象