简体   繁体   English

外键约束的实体框架异常

[英]Entity Framework exception on foreign key constraint

I have a simple person 我有一个简单的人

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

And if one person sends a friend request to some one else, I have this model 如果一个人向另一个人发送朋友请求,我就拥有这种模式

 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; }
    }

I am using EF 4.1 code first approach. 我正在使用EF 4.1代码优先方法。 Two tables should get created 应该创建两个表

People {Columns = "Id, Name"}

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

with foreign key constraints... 带有外键约束...

When I Try to add a new person from my controller it complains 当我尝试从控制器添加新人员时,它抱怨

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

InnerException: 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.

What Am I doing wrong? 我究竟做错了什么? Am I missing any annotation on my model? 我在模型上缺少任何注释吗?

Or is this a completely incorrect way of handling Friend Request send-receive-accept scenario? 还是这是处理“朋友请求”发送-接收-接受方案的完全错误的方式?

Any Help is appreciated. 任何帮助表示赞赏。

You can define the relationships with cascade delete false in model building, 您可以在模型构建中使用层叠删除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);

     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM