简体   繁体   中英

Entity Framework 5, Code First Many to Many foreign key mapping with extra property

I have these classes

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

I want UserSecretQuestion to be a join table holding the user's Answer. The problem is that EF5 won't create this table for me because it claims I need a key on that table.

so of course putting public int Id { get; set; } in there will fix it but that puts a field I don't need in my database.

Is there a way to make this work properly so that the secretquestionid and userid foreign keys form a composite key for the usersecretquestion table.

I note that there are a few questions on here that talk about many to many relationships but none (that I can find) talk about this kind of relationship where the entity has extra data eg 'Answer'.

First you have to add SecretQuestionId and UserId as properties to the UserSecretQuestion class.

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

You then have to override the OnModelCreating method in your DbContext class and tell Entity Framework to use composite keys for the join table.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM