I have a many to many relationship and I want to store extra data in the couple-table, using Code First Fluent API.
How can this be achieved ?
My model:
You cannot map it as many-to-many directly. If you add additional field to the junction table and you want to access that field in the application you need to promote your junction table to entity instead and use two one-to-many relations:
public class Badge {
...
public virtual ICollection<UserBadge> UserBadges { get; set; }
}
public class User {
...
public virtual ICollection<UserBadge> UserBadges { get; set; }
}
public class UserBadge {
public int UserId { get; set; }
public int BadgeId { get; set; }
public string B { get; set; }
public virtual Badge Badge { get; set; }
public virtual User User { get; set; }
}
The default conventions should define the mapping correctly except the key for UserBadge
table which must be done either in Fluent-API or data annotations.
modelBuilder.Entity<UserBadge>().HasKey(e => new { e.UserId, e.BadgeId });