问题描述
我有很多关系,我想使用Code First 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.
如何实现?
我的型号:
用户可以拥有1个或多个徽章(可选),徽章可以属于一个或多个用户(可选)。我想存储一个额外的字段(称为B),用于存储这个关系。该表应该命名为UserBadges,具有以下字段:UserId,BadgeId,B
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
(我已经在StackOverflow ,但是我的模型有点复杂,没有正确答案) / p>
(I have seen this earlier in StackOverflow here, but I the model is somewhat complex and no answer has been given correctly yet)
推荐答案
您无法直接映射到多对多。如果您向结点表添加其他字段,并且要访问该应用程序中的该字段,则需要将结点表升级到实体,并使用两个一对多关系:
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; }
}
默认约定应正确定义映射,除 UserBadge
表必须在Fluent-API或数据注释中完成。
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 });
这篇关于在Fluent API中与多个字段进行多对多映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!