EF Codefirst - 使用流畅 API 的表映射

本文关键字:API 映射 Codefirst EF | 更新日期: 2023-09-27 17:56:02

我有以下类:

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 的实体类型配置,它们是:

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

这是一个简单的聊天应用程序。 如果我是当前用户,那么我是消息的发送者。收件人用户是我要向其发送邮件的用户。请建议我如何配置我的实体类型配置。我收到以下错误:违反了多重性约束。关系"DataAcessLayer.Conversation_RecipientUser"的角色"Conversation_RecipientUser_Target"具有多重性 1 或 0..1。

EF Codefirst - 使用流畅 API 的表映射

删除此部分

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

来自对话配置

我更新了我的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 服务器错误:多个级联路径)。它奏效了。感谢您的帮助!!