Peter
Peter

Reputation: 7804

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 e.g. 'Answer'.

Upvotes: 2

Views: 3372

Answers (1)

HTX9
HTX9

Reputation: 1717

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

Upvotes: 3

Related Questions