FOREIGN KEY可能导致循环或多个级联路径异常

时间:2014-02-13 08:42:58

标签: c# sql-server entity-framework

我正在尝试使用EF Code First方法创建数据库。

我有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);

在创建模型时,它会在System.Data.SqlClient.SqlException中抛出EntityFramework.dll

消息:

Introducing FOREIGN KEY constraint 'FK_dbo.DBGroupMessages_dbo.DBUsers_OwnerID' on table 'DBGroupMessages' may cause cycles or multiple cascade paths.

Google没有帮助我-_-

2 个答案:

答案 0 :(得分:0)

它在一个不同的表上抛出一个异常而不是你正在调用WillCascadeOnDelete(false)。 FK约束在DBGroupMessages表上。我对Fluent API的语法并不十分熟悉,但你应该在Stack Overflow上找到一些很好的例子。

例如this one

答案 1 :(得分:0)

您的实体设计中发生了循环递归。 可能的解决方案是更改DBGroupMessage类,如下所示

public class DBGroupMessage
{
    public DBGroup Group { get; set; }    
    [Required]
    public Guid GroupID { get; set; }    
    public Guid Id { get; set; }    
    public DBUser Owner { get; set; }    
    public Guid? OwnerID { get; set; }
}

我建议将所有者设为可选。 我希望这可以解决你的问题。