Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths

后端 未结 2 1113
滥情空心
滥情空心 2020-11-30 01:01

I am getting this error

Introducing FOREIGN KEY constraint \'FK_dbo.Regions_dbo.Countries_CountryId\' on table \'Regions\' may cause cycles or mul

相关标签:
2条回答
  • 2020-11-30 01:07

    Add modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>() in OnModelCreating method of your DataContext file as follow:

    public class YourDataContext : DbContext
    {
        public DbSet<Country> Countries{ get; set; }
        ...
    
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    
        }
    }
    

    The same question: entity-framework-how-to-solve-foreign-key-constraint-may-cause-cycles-or-multi

    0 讨论(0)
  • 2020-11-30 01:08

    All relationships in your model are required because all foreign key properties (CountryId, RegionId, CityId) are not nullable. For required one-to-many relationships EF will enable cascading delete by convention.

    Country and Region have multiple delete paths to the Store table, for example if you delete a Country the related Stores can be deleted via three different cascading paths (which is not allowed with SQL Server):

    • Country -> Store
    • Country -> Region -> Store
    • Country -> Region -> City -> Store

    You must avoid such ambiguous delete paths by either disabling cascading delete using Fluent API or by defining some of the relationships as optional (with a nullable foreign key Guid?).

    Or remove the Stores collections (and the inverse references and FK properties) from all entities except City. To me those collections look redundant because you can find all stores in a Country by navigating through the Regions.Cities.Stores collections.

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