我有以下课程:
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; }
}
我使用流畅的Api使用EntityTypeConfiguration:
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。我收到的错误如下:违反了多重性约束。角色&#39; Conversation_RecipientUser_Target&#39;关系&#39; DataAcessLayer.Conversation_RecipientUser&#39;具有多重性1或0..1。
答案 0 :(得分:0)
删除此部分
HasRequired(x => x.RecipientUser).WithMany(x => x.Conversations);
来自ConversationConfig的
答案 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错误:多个级联路径)。 这很有效。 谢谢你的帮助!!!