Entity Framework Code First: FOREIGN KEY constraint may cause cycles or multiple cascade paths

前端 未结 2 788
离开以前
离开以前 2020-12-31 04:22

Entity Framework Code First can generate the DB for the following POCOs.

public class Item {
    public int Id { get; set; }
    public string Name { get; se         


        
相关标签:
2条回答
  • 2020-12-31 05:06

    My expectation is that in the first case your Id properties are not used in the database as FKs and EF will create another two columns (you can validate this by forcing pairing of navigation property with FK property using ForeignKeyAttribute). In the second case EF will correctly recognize your properties but it will also use cascade delete convention which will cause error in SQL server. You have two properties from the table pointing to the same parent. Actually in the database you can createItemPair from the same Item (both FKs set to the same Id). If both relations have cascade delete enabled it will result in multiple cascade paths => not allowed in SQL server.

    The solution here is fluent mapping to manually define how the relations are mapped. Here is the example.

    0 讨论(0)
  • 2020-12-31 05:10

    I decided to just remove the cascade delete convention.

     protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
            modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
    
        }
    

    The reasons are:

    • I prefer to mark records deleted or deactivated for audit purposes.
    • At most I delete just the junction / mapping tables.
    • With an ORM It is relatively trivial to loop through and delete child records in the rare case I need to.

    Thank you Ladislav Mrnka pointing me in the right direction.

    0 讨论(0)
提交回复
热议问题