简体   繁体   中英

Mapping lookup/junction table entity in many-to-many relationship

I'm attempting to map a many-to-many relationship and include the lookup/junction table entity and I'm having some trouble. Here are my (basic) models:

public class User
{
    public int UserId { get; set; }
    public IList<UserGroupCode> Codes { get; set; }
}

public class Group
{
    public int GroupId { get; set; }
    public IList<UserGroupCode> Codes { get; set; }
}

public class UserGroupCode
{
    public int UserGroupCodeId { get; set; }
    public int UserId { get; set; }
    public int GroupId { get; set; }
    public string Value { get; set; }
}

Here is the configuration for User I've been working with

HasMany(p => p.Codes).WithMany().Map(m =>
{
    m.ToTable("UserGroupCodes");
    m.MapLeftKey("UserId");
    m.MapRightKey("UserGroupCodeId");
});

I've seen a lot of articles on how to map many-to-many relationships which don't include the lookup table as an entity (the classic example is User-Roles relationships). But, as you can see, I have a Value property on my UserGroupCode relationship which necessitates that relationship being an actual entity.

Thanks in advance.

I ended up coming across this article. I added navigation properties to my UserGroupCode model for User and Group .

public class UserGroupCode
{
    public int UserGroupCodeId { get; set; }
    public int UserId { get; set; }
    public User User { get; set; }
    public int GroupId { get; set; }
    public Group Group { get; set; }
    public string Value { get; set; }
}

The only configuration required for the relationship is on the UserGroupCode entity:

HasRequired(p => p.User).WithMany(p => p.Codes).HasForeignKey(p => p.UserId);
HasRequired(p => p.Group).WithMany(p => p.Codes).HasForeignKey(p => p.GroupId);

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