I`m gettng the following error in EF Core: No backing field could be found for property 'ParentId' of entity type 'Child' and the property does not have a getter.
This is my configuration for the Child entity:
// 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");
And my entities:
public class Parent
{
public int Id { get; set; }
}
public class Child
{
public Parent Parent { get; private set; }
public void SetParent(Parent p) => Parent = p;
}
The error occurs when I call 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)):
If I add the shadow property as a real property to the model as such:
public class Child
{
public int ParentId { get; set;}
public Parent Parent { get; private set; }
public void SetParent(Parent p) => Parent = p;
}
then everything works. But I'd like to keep it a shadow property if possible.