外键约束可能导致循环或多个级联路径

时间:2017-02-21 19:05:27

标签: entity-framework asp.net-core entity-framework-core ef-fluent-api

我的.NET CORE项目中的迁移出现以下错误Foreign Key constraint may cause cycles or multiple cascade paths。我有这3个身份:

public class Post
{
        [Key]
        public long Id { get; set; }

        [Required]
        public long UserID { get; set; }
        public virtual ApplicationUser User { get; set; }

        ...
}

public class Album
{
        [Key]
        public long Id { get; set; }

        [Required]
        public long UserID { get; set; }
        public virtual ApplicationUser User { get; set; }

        ...
}

public class PostAlbum
{
        public long PostID { get; set; }
        public virtual Post Post { get; set; }

        public long AlbumID { get; set; }
        public virtual Album Album { get; set; }
}

我使用流畅的api来映射实体PostAlbum的外键:

builder.Entity<PostAlbum>(x =>
{
                x.HasKey(y => new { y.PostID, y.AlbumID });
                x.HasOne(y => y.Post).WithMany().HasForeignKey("PostID").OnDelete(DeleteBehavior.Cascade);
                x.HasOne(y => y.Album).WithMany().HasForeignKey("AlbumID").OnDelete(DeleteBehavior.Cascade);
});

逻辑:帖子可以存储在很多专辑中,而专辑可以有很多帖子。

问题在于,如果我将DeleteBehavior更改为DeleteBehavior.Restrict,我将无法删除Post实体,因为它与PostAlbum的外键冲突。

错误:

enter image description here

有人可以帮助我吗?

0 个答案:

没有答案