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. 

我在做什麼錯?我是否在模型上缺少任何註釋?

或者這是一個完全不正確的處理好友請求send-receive-accept場景的方式嗎?

任何幫助表示讚賞。

+0

也許這將有助於。 http://stackoverflow.com/questions/851625/foreignkey-constraint-may-cause-cycles-or-multiple-cascade-paths – MStp

回答

1

您可以定義與級聯關係刪除模型建立假的,

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

    }