簡體   English   中英

實體框架,外鍵約束可能會導致循環或多個級聯路徑

[英]Entity Framework, Foreign key constraint may cause cycles or multiple cascade paths

我首先為項目使用實體代碼。 基本上我有3類UsersBranchsUsersBranchs

Users包含UserIDName ,...

Branchs包含BranchIDLocation ,...和UserID,這是指分支的創建者,而UsersBranchs僅具有兩列BranchID和UserID,用於定義哪個用戶位於哪個分支中

問題是我收到此錯誤:

表“ UsersBranchs”上的“ FK_dbo.UsersBranchs_dbo.Users_UsersID”可能會導致循環或多個級聯路徑。 指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY約束。

你能幫我嗎?

更新
這是UsersBranchs類

[ForeignKey("UserID")]
public CoreUsers User { get; set; }
public Guid UsersID { get; set; }

[ForeignKey("BranchID")]
public Branchs Branch { get; set; }
public Guid BranchID { get; set; }


並將此行添加到DbContext類以使用UserID和BranchID作為鍵

modelBuilder.Entity<UsersBranchs>().HasKey(x => new { x.UserID, x.BranchID });


分支機構現為

   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   [Key]
   public Guid ID { get; set; }

   [ForeignKey("UserID")]
   public CoreUsers User { get; set; }
   public Guid UserID { get; set; }

   public .....


現“用戶類別”為

   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   [Key]
   public Guid ID { get; set; }

   public .....

長期以來,Sql Server一直無法處理多個級聯路徑並無法將其級聯刪除到同一表 僅Google錯誤消息。 基本上,如果要使用級聯刪除,則必須確保只有一個級聯路徑。

目前,您有兩個來自Branchs-> UsersBranchs和Branchs-> Users-> UsersBranchs的路徑。

EF默認情況下會設置級聯刪除,但是可以通過刪除DbContext中的約定來停止它。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Manually set cascade delete behaviour
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

    base.OnModelCreating(modelBuilder);
}

然后,您必須在要級聯刪除的任何關系上設置WillCascadeOnDelete(true)。 請參閱實體框架文檔

除此之外,您的模型似乎有些奇怪。 您看起來好像在嘗試創建多對多鏈接/聯接表UsersBranchs,但是在Branchs上也只有一個User並沒有什么意義。 在這種情況下,您甚至需要UsersBranchs表嗎? 您是否意味着在分支機構上擁有一組用戶,即導航屬性而不是外鍵,從而提供了一對多關系“分支機構->用戶”?

順便說一句,我真的不喜歡對單個實體使用復數。

我認為您遇到了問題,因為您沒有告訴Entity Framework在層疊刪除時如何處理這些類

在您的DbContext類中,重寫OnModelCreating方法並編寫此代碼

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{    
     modelBuilder.Entity<UserBranch>()
         .HasRequired(t => t.CoreUsers)
         .WithMany()
         .HasForeignKey(t => t.UserID)
         .WillCascadeOnDelete(false);

     modelBuilder.Entity<UserBranch>()
         .HasRequired(t => t.Branch)
         .WithMany()
         .HasForeignKey(t => t.BranchID)
         .WillCascadeOnDelete(false);

     modelBuilder.Entity<Branch>()
         .HasRequired(t => t.User)
         .WithMany()
         .HasForeignKey(t => t.UserID)
         .WillCascadeOnDelete(false);
}

希望這個能對您有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM