外键约束的实体框架异常

时间:2011-09-19 00:04:53

标签: c# asp.net-mvc asp.net-mvc-3 entity-framework entity-framework-4.1

我有一个简单的人

 public class Person
    {
        public virtual string Id { get; set; }
        public virtual string Name { get; set; }            
    }

如果有人向其他人发送朋友请求,我就有这个模型

 public class FriendRequest
    {
        public int Id { get; set; }        
        public bool Accepted { get; set; }

        [Key, Column(Order = 1)]
        public string SenderId { get; set; }    
        public virtual Person Sender { get; set; }

        [Key, Column(Order = 2)]
        public string ReceiverId { get; set; }
        public virtual Person Receiver { get; set; }
    }

我使用EF 4.1代码第一种方法。应该创建两个表

People {Columns = "Id, Name"}

FriendRequests {Columns = "Id, SenderId, ReceiverId, Accepted"} 

有外键约束......

当我尝试从我的控制器中添加新人时,它会抱怨

The database creation succeeded, but the creation of the database objects did not. 
See  InnerException for details.

的InnerException:

Introducing FOREIGN KEY constraint 'FriendRequest_Sender' on table 
'FriendRequests' may cause cycles or multiple cascade paths. 
Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify 
other FOREIGN KEY constraints.Could not create constraint.

我做错了什么?我错过了我的模型上的任何注释吗?

或者这是处理朋友请求发送 - 接收 - 接受方案的完全错误的方法吗?

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您可以在模型构建中使用cascade delete false定义关系

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

     modelBuilder.Entity<FriendRequest>().
      HasRequired(f=>f.Sender ).WithMany().HasForeignKey(f=>f.SenderId ).WillCascadeOnDelete(false);
      modelBuilder.Entity<FriendRequest>().
      HasRequired(f=>f.Receiver ).WithMany().HasForeignKey(f=>f.ReceiverId ).WillCascadeOnDelete(false);

     }

答案 1 :(得分:0)