我正在嘗試使用EF Code First方法創建數據庫。FOREIGN KEY可能導致週期或多個級聯路徑異常
我有3個關係表。
+--------+ +---------+
| Users | | Groups |
+--------+ +---------+
| | -----------> | |
|________| |_________|
| |
| +--------------+ |
+---> |Group Messages| <---+
+--------------+
| |
|______________|
箭頭表示級聯刪除方向。
public DBUser()
{
GroupMessages = new Collection<DBGroupMessage>();
Groups = new Collection<DBGroup>();
}
public Guid Id { get; set; }
public virtual ICollection<DBGroupMessage> GroupMessages { get; set; }
public virtual ICollection<DBGroup> Groups { get; set; }
public class DBGroup
{
public DBGroup()
{
GroupMessages = new Collection<DBGroupMessage>();
}
public Guid Id { get; set; }
[Required]
public Guid OwnerID { get; set; }
public DBUser Owner { get; set; }
public virtual ICollection<DBGroupMessage> GroupMessages { get; set; }
}
public class DBGroupMessage
{
public DBGroup Group { get; set; }
[Required]
public Guid GroupID { get; set; }
public Guid Id { get; set; }
public DBUser Owner { get; set; }
[Required]
public Guid OwnerID { get; set; }
}
使用Fluent API定義PK和FK。
modelBuilder.Entity<DBGroup>().HasKey(t => t.Id);
modelBuilder.Entity<DBGroup>().HasRequired(t => t.Owner).WithMany(t => t.Groups);
modelBuilder.Entity<DBGroupMessage>().HasKey(t => t.Id);
modelBuilder.Entity<DBGroupMessage>().HasRequired(t => t.Owner).WithMany(t => t.GroupMessages);
modelBuilder.Entity<DBGroupMessage>().HasRequired(t => t.Group).WithMany(t => t.GroupMessages);
modelBuilder.Entity<DBUser>().HasKey(t => t.Id);
modelBuilder.Entity<DBUser>().HasMany(t=>t.GroupMessages).WithRequired(t=>t.Owner).WillCascadeOnDelete(false);
在創建模型,可以拋出EntityFramework.dll
System.Data.SqlClient.SqlException
。
消息:
Introducing FOREIGN KEY constraint 'FK_dbo.DBGroupMessages_dbo.DBUsers_OwnerID' on table 'DBGroupMessages' may cause cycles or multiple cascade paths.
谷歌沒有幫助我-_-
我明白問題,但不明白解決這個問題的方法。 GroupMessages(表中最後一個代碼字符串)的表DBUser中已禁用級聯更新。 – SUDALV