Entity Framework: how to solve “FOREIGN KEY constraint may cause cycles or multiple cascade paths”?

ⅰ亾dé卋堺 提交于 2019-11-26 20:20:39

You can use the fluent api to specify the actions the error message suggests.

In your Context:

protected override void OnModelCreating( DbModelBuilder modelBuilder )
{
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<aspnet_UsersInRoles>().HasMany(i => i.Users).WithRequired().WillCascadeOnDelete(false);
}

Note that you have not included the definition for the table aspnet_UsersInRoles so this code may not work.

Another option is to remove all CASCADE DELETES by adding this

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

If you need more info about configuring relationships with the fluent api I suggest http://msdn.microsoft.com/en-US/data/jj591620

feeeper

Also you can modify your migration class. In my case in the migration class was:

CreateTable(
    "dbo.Spendings",
    c => new
        {
          SpendingId = c.Int(nullable: false, identity: true),
          CategoryGroupId = c.Int(nullable: false),
          CategoryId = c.Int(nullable: false),
          Sum = c.Single(nullable: false),
          Date = c.DateTime(nullable: false),
          Comment = c.String(),
          UserId = c.String(),
          LastUpdate = c.String(),
        })
    .PrimaryKey(t => t.SpendingId)
    .ForeignKey("dbo.Categories", t => t.CategoryId, cascadeDelete: true)
    .ForeignKey("dbo.CategoryGroups", t => t.CategoryGroupId, cascadeDelete: true)
    .Index(t => t.CategoryGroupId)
    .Index(t => t.CategoryId);

After removing "cascadeDelete: true" Update-Database works perfectly.

OR as false

 .ForeignKey("dbo.Categories", t => t.CategoryId, cascadeDelete: false)
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    }

Add this code in context

Based on your comments, the problem is that you're using the same PK in both tables. I'd change that right away, have Users PK as an extra field in Employees with a FK relationship to Users (one to one i guess). And add an independent PK to users (Another guid to respect the rest of your tables). If you want to guarantee that the new foreign key in Employees (the one that points to Users) is unique, you can always add a Unique Index.

That way you keep your structure all the same and you get rid of the cycle.

Just an Update:

As other answers suggest you need to NOT do any action on delete. Updated way of doing this is as follows for Entityframework Core 1.0

table.ForeignKey(name: "FK_Cities_Regions_RegionId",
                 column: x => x.RegionId,
                 principalTable: "Regions",
                 principalColumn: "RegionId",
                 onDelete: ReferentialAction.NoAction);

NOTE: Do ReferentialAction.NoAction on onDelete

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