2016-07-07 147 views
0

我有以下類表映射:EF Codefirst - 用流利的API

public class User 
{   
    public Guid Id { get; set; } 
    public string Name { get; set; } 
    public bool Active { get; set; } 
    public string UserName { get; set; }  
    //keys  
    public ICollection<Conversation> Conversations { get; set; } 
} 
public class Conversation 
{   
    public Guid ID { get; set; } 
    public ICollection<Message> Messages { get; set; } 
    public User RecipientUser { get; set; } 
    public User SenderUser { get; set; } 
    public DateTime CreatedDate { get; set; } 
    public DateTime ModifiedDate { get; set; } 
} 

我使用EntityTypeConfiguration用流利的API,它是:

public class UserConfig : EntityTypeConfiguration<User> 
{ 
    public UserConfig() 
    { 
     HasMany(x => x.Conversations).WithRequired(x => x.RecipientUser); 
    } 
} 
public class ConversationConfig : EntityTypeConfiguration<Conversation> 
{ 
    public ConversationConfig() 
    { 
     HasKey(x => x.ID); 
     HasRequired(x => x.RecipientUser).WithMany(x => x.Conversations);     
    } 
} 

這是一個簡單的聊天應用程序。如果我現在是用戶而不是我是消息的發送者。收件人用戶是我正在向我發送信息的用戶。 請建議我如何配置我的EntityTypeConfiguration。我遇到如下錯誤:違反了多重性約束。關係「DataAcessLayer.Conversation_RecipientUser」的角色'Conversation_RecipientUser_Target'具有多重性1或0..1。

回答

0

我更新了我的Conversation類,如下所示:

public class Conversation 
{ 
    public int ID { get; set; } 
    public int SenderUserID { get; set; } 
    public User SenderUser { get; set;} 
    public int RecipientUserID { get; set; } 
    public User RecipientUser { get; set; } 
} 

和刪除我UserConfig流利的API。相反,我在ConversationConfig.cs文件添加映射爲:

public class ConversationConfig : EntityTypeConfiguration<Conversation> 
{ 
    public ConversationConfig() 
    { 
     HasKey(c => c.ID); 
     HasRequired(c => c.SenderUser).WithMany(u => u.Conversations) 
          .HasForeignKey(c => c.SenderUserID).WillCascadeOnDelete(true); 
     HasRequired(c => c.RecipientUser).WithMany() 
          .HasForeignKey(c => c.RecipientUserID).WillCascadeOnDelete(false);   
    } 
} 

(其中一個外鍵不具備級聯刪除,因爲這會導致SQL-Server錯誤:多階路徑)。 它的工作。 感謝您的幫助!

0

刪除這部分

HasRequired(x => x.RecipientUser).WithMany(x => x.Conversations); 

從ConversationConfig

+0

對不起,但仍然有錯誤。 –

+0

我在我的機器上試過了你的代碼,我剛剛刪除了HasRequired(x => x.RecipientUser).WithMany(x => x.Conversations)部分,因爲這在你的UserConfig,HasMany(x => x .Conversations).WithRequired(x => x.RecipientUser)。你只應該聲明一次。 –

+0

嗨@Patrick請檢查我的答案。謝謝。 –