![](/img/trans.png)
[英]No backing field could be found for property of entity type and the property does not have a getter
[英]EF Core: No backing field could be found for property of entity type and the property does not have a getter
我在 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)):
如果我将阴影属性作为真实属性添加到 model 中,如下所示:
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,异常消失了,说明已经上报/识别并修复。 因此,您可以简单地升级到该版本。
原来的:
阴影属性的配置很好。 不幸的是,您遇到了 EF Core 3.x 错误之一。
为了将Contains
方法转换为 SQL,EF Core 必须将其转换为 PK 相等比较,类似于(在伪代码中)
dbContext.Children.Any(c => PK(c) == PK(myChild))
从异常堆栈跟踪中可以看出,当 PK 是影子属性时显然没有这样做。
我目前检查了最新的 EF 5 预览版,它似乎已修复(问题消失了)。 因此,在它发布之前,解决方法是将隐式实体相等比较(例如Contains(entity)
、 Equals(entity)
、 == 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)
(正确的 SQL 翻译与 v5.0 相同,但使用“魔术”字符串并需要明确指定影子属性名称和类型)
public class Child
{
public int ParentId{get;set;}
public Parent Parent { get; private set; }
public void SetParent(Parent p) => Parent = p;
}
你应该定义你的外键变量并记住私有集不会在数据库中创建关系
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.