桌上的复合键与其他属性

时间:2014-05-26 08:12:43

标签: c# entity-framework ef-code-first entity-framework-6

我在一个不是联结表的表上有一个复合键,因为它包含另一个字段,一个订单属性。

我遇到各种问题,让复合键工作。这就是基础:

public class User : BaseModel
{

    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }

    public virtual ICollection<UserQuestionGroup> QuestionGroups { get; set; }

    // ..... //
}

public class QuestionGroup
{
    public int Id { get; set; }
    public virtual ICollection<User> Users { get; set; }
    // ..... //
}

// This is where I'm having problems with the mapping
public class UserQuestionGroup
{        

    [Key,ForeignKey("User"), Column(Order = 0)]
    public int UserId;

    [Key, ForeignKey("QuestionGroupId"), Column(Order = 1)]
    public int QuestionGroupId;

    public virtual User User { get; set; }

    public virtual QuestionGroup QuestionGroup { get; set; }

    [Column("Sort")]
    public int Order { get; set; }
}

这是我得到的错误:

One or more validation errors were detected during model generation:

Plus.DAL.UserQuestionGroup: : EntityType 'UserQuestionGroup' has no key defined. Define the key for this EntityType.
UserQuestionGroups: EntityType: EntitySet 'UserQuestionGroups' is based on type 'UserQuestionGroup' that has no keys defined.

每个用户可以拥有多个问题组,每个问题组可以拥有多个用户。我正在使用存储库模式来访问数据访问层(DAL)。

有人可以指出我正确的方向,如果可能的话,使用属性或使用DbModelBuilder。

我正在使用EF 6和MVC 5.1。

谢谢, 里斯

1 个答案:

答案 0 :(得分:2)

将字段从字段更改为属性。此外,您应使用ForeignKey属性标记导航属性,而不是键:

[Key, Column(Order = 0)]
public int UserId { get; set; }

[Key, Column(Order = 1)]
public int QuestionGroupId { get; set; }

[ForeignKey("UserId")]
public virtual User User { get; set; }

[ForeignKey("QuestionGroupId")]
public virtual QuestionGroup QuestionGroup { get; set; }

这将生成以下表格:

enter image description here

注意:我建议您使用符合Code First的流畅映射API,这样可以使您的实体与数据库相关的属性保持清晰。可以通过以下方式完成相同的映射:

public class UserQuestionGroupMap : EntityTypeConfiguration<UserQuestionGroup>
{
    public UserQuestionGroupMapping()
    {
        HasKey(uqg => new { uqg.UserId, uqg.QuestionGroupId });
        Property(uqg => uqg.Order).HasColumnName("Sort");

        HasRequired(uqg => uqg.User)
            .WithMany(u => u.QuestionGroups).HasForeignKey(uqg => uqg.UserId);

        HasRequired(uqg => uqg.QuestionGroup)
            .WithMany().HasForeignKey(uqg => uqg.QuestionGroupId);
    }
}

然后只需在DbContext中创建模型时将模型生成器添加到模型构建器:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new UserQuestionGroupMap());
    // add other maps
    base.OnModelCreating(modelBuilder);
}