简体   繁体   中英

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

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,

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

     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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