Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

前端 未结 18 931
天涯浪人
天涯浪人 2020-11-22 02:37

I\'ve been wrestling with this for a while and can\'t quite figure out what\'s happening. I have a Card entity which contains Sides (usually 2) - and both Cards and Sides h

18条回答
  •  抹茶落季
    2020-11-22 03:04

    Here's what I did. This will apply to all Circular relationships, hence you don't have to specify one by one inside OnModelCreating.

    Steps

    1. Remove last migration (dotnet ef migrations remove)
    2. Add the following code snippet in your OnModelCreating

    var cascadeFKs = modelBuilder.Model.GetEntityTypes()
        .SelectMany(t => t.GetForeignKeys())
        .Where(fk => !fk.IsOwnership && fk.DeleteBehavior == DeleteBehavior.Cascade);
    
    foreach (var fk in cascadeFKs)
        fk.DeleteBehavior = DeleteBehavior.Restrict;

    1. Create new migrations
    2. Update database

    This did the trick for me.

提交回复
热议问题