【问题标题】:Entity Framework 5, Code First Many to Many foreign key mapping with extra property实体框架 5,代码优先的多对多外键映射,具有额外的属性
【发布时间】:2012-11-11 10:18:06
【问题描述】:

我有这些课程

public class SecretQuestion
{
    [Key]
    public int SecretQuestionId { get; set; }
    [Required]
    public string Caption { get; set; }
}

public class UserSecretQuestion
{
    public SecretQuestion SecretQuestion { get; set; }
    public User User { get; set; }

    [Required]
    public string Answer { get; set; }
}

public class User
{
    [Key]
    public int UserId { get; set; }
    public string Email { get; set; }
    public string UserName { get; set; }
}

我希望 UserSecretQuestion 是一个包含用户答案的​​连接表。问题是 EF5 不会为我创建此表,因为它声称我需要该表上的密钥。

所以当然把 public int Id { get;放; } 在那里会修复它,但这会在我的数据库中放置一个我不需要的字段。

有没有办法让它正常工作,以便 secretquestionid 和 userid 外键形成 usersecretquestion 表的复合键。

我注意到这里有几个问题谈论多对多关系,但没有(我能找到)谈论实体具有额外数​​据的这种关系,例如'答案'。

【问题讨论】:

    标签: c# sql asp.net-mvc entity-framework-5 composite-key


    【解决方案1】:

    首先,您必须将SecretQuestionIdUserId 作为属性添加到UserSecretQuestion 类。

    public class UserSecretQuestion
    {
        [Key, ForeignKey("SecretQuestion")]
        public int SecretQuestionId { get; set; }
    
        [Key, ForeignKey("User")]
        public int UserId { get; set; }
    
        [Required]
        public string Answer { get; set; }
    
        public SecretQuestion SecretQuestion { get; set; }
        public User User { get; set; }
    }
    

    然后,您必须覆盖 DbContext 类中的 OnModelCreating 方法,并告诉 Entity Framework 为连接表使用复合键。

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Set composite keys
        modelBuilder.Entity<UserSecretQuestion>().HasKey(k => new { k.SecretQuestionId, k.UserID });
    }
    

    【讨论】:

    • 我会在星期一回去工作的时候检查一下……虽然看起来不错,但谢谢
    • 我不需要数据注释。
    猜你喜欢
    • 1970-01-01
    • 2012-05-10
    • 2015-05-02
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多