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

佐手、 提交于 2019-11-30 08:36:08
Ladislav Mrnka

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!