I have a EF Code First One-To-Many relationship. It’s essentially a Parent/Child relations as the child can’t exist without the parent.
public class Parent
{
[Key]
public Guid Id { get; set; }
public virtual ICollection<Child> Children { get; set; }
public virtual ICollection<OtherChild> OtherChildren { get; set; }
}
public class Child
{
[Key]
public Guid Id { get; set; }
public virtual Parent Parent { get; set; }
}
So I wasn’t sure how I could have the child be required to have a Parent so I tried putting a [Required] attribute on it. That gave me the error:
- InnerException {"Introducing FOREIGN KEY constraint 'Child_Parent' on table 'Child'
may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE
NO ACTION, or modify other FOREIGN KEY constraints.\r\nCould not create constraint.
See previous errors."}
System.Exception {System.Data.SqlClient.SqlException}
Ok I’m not sure how he could have multiple cascading parts.
The parent also has other child objects and those child objects share a many-to-many relationship with the original child object but it shouldn’t require a cascade delete.
I guess I’m doing this wrong but what is the proper way to do this.
PS. When I have a child require a parent should I make the foreign key a part of the primary key?
You can disable cascading delete for the relationship in Fluent API (it’s not possible with data annotations):
You must delete the children then as well in your code if you delete a parent.
You don’t need to make the foreign key part of the primary key and I don’t see a benefit in doing so. Your Guid key is already unique. It will help query performance though if you create an index on the foreign key column in the database.