【问题标题】:EF Codefirst - table mapping using fluent apiEF Codefirst - 使用流利的 api 进行表映射
【发布时间】:2016-07-07 11:37:47
【问题描述】:

我有以下课程:

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

这是一个简单的聊天应用程序。如果我是 currentUser,那么我就是消息的发送者。收件人用户是我要向其发送消息的用户。 请建议我如何配置我的 EntityTypeConfiguration。我收到如下错误:违反了多重性约束。关系“DataAcessLayer.Conversation_RecipientUser”的角色“Conversation_RecipientUser_Target”的多重性为 1 或 0..1。

【问题讨论】:

    标签: c# asp.net entity-framework ef-code-first


    【解决方案1】:

    删除这部分

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

    来自对话配置

    【讨论】:

    • 我在我的机器上尝试了你的代码,我刚刚删除了 HasRequired(x => x.RecipientUser).WithMany(x => x.Conversations) 部分,因为这在你的 UserConfig 中做同样的事情, HasMany(x => x.Conversations).WithRequired(x => x.RecipientUser)。你应该只声明一次。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-28
      • 2010-11-06
      • 2011-07-19
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 2012-12-09
      • 2012-04-13
      相关资源
      最近更新 更多