Consider the following two entities*:
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Child PrimaryChild { get; set; }
public virtual Child SecondaryChild { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
// Foreign keys to be added here or
// in the other class (that's what I'm trying to figure out)
}
As the code shows, a parent needs to have a primary child and a secondary child; and (preferably) when the parent is deleted, both children should be deleted as well.
Is it even possible to represent such relationship with EF?
If the parent were to have only one child, I could easily use a one-to-one relationship (1 to 0..1) by turning the primary key of Child into both PK and FK. Obviously, that doesn't work with the current situation because, for one, a primary key cannot have multiple values.
This feels like it's a common enough situation that it should have a well-known solution. However, after checking countless posts, I still can't find one. The closest thing I could find is this answer but it doesn't work because:
It creates
* to 0..1relationships.When I ignored that fact and tried to execute the following code:
var c1 = new Child { Name = "C1" }; var c2 = new Child { Name = "C2" }; context.Parents.Add(new Parent { Name = "P1", PrimaryChild = c1, SecondaryChild = c2 });...it threw a DbUpdateException with the message:
Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
How can this problem be solved?
* This is a simplified example. In the real life scenario, there are relationships between the parent and other child entities with two or more references to each.