【发布时间】:2020-08-14 17:37:20
【问题描述】:
我在 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;
}
然后一切正常。但如果可能的话,我想保留它的影子属性。
【问题讨论】:
标签: c# entity-framework entity-framework-core