I have the following code:
public class Parent
{
public int ParentId {get;set;}
public ICollection<Child> Children {get;set;}
}
public class Child
{
public int ChildId {get;set;}
public Parent Parent {get;set;}
}
It's mapped as one-to-many by EF without any additional efforts. When I replace Children with new collection (with 3 another items) I have old orphan entities in child-table like this:
Id | Parent_Id
1 NULL <-- orphan
2 NULL <-- orphan
3 NULL <-- orphan
4 1 <-- new
5 1 <-- new
6 1 <-- new
I want to get rid of them with identifying relationship explicitly:
modelBuilder.Entity<Child>().HasKey(x => new { x.ChildId, x.ParentId });
modelBuilder.Entity<Parent>().HasMany(x => x.Children).WithRequired().HasForeignKey(x => x.ParentId);
But I don't have ParentId property in children. I have only "Parent" pointing directly to the parent entity. If I try
modelBuilder.Entity<Child>().HasKey(x => new { x.ChildId, x.Parent });
I get an error message:
The property ... cannot be used as a key property on the entity ... because the property type is not a valid key type
Is there any way remove all unnecessary orphans?