Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

entity framework - Many to many mapping with extra fields in Fluent API

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:

A user can have 1 or more badges (optional), a badge can belong to one or more users (optional). I want to store an extra field (called B) for this relation to be stored. The table should be named UserBadges with the following fields: UserId, BadgeId, B

(I have seen this earlier in StackOverflow here, but I the model is somewhat complex and no answer has been given correctly yet)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...