我在 MongoDB 中有两个具有多对多关系的集合。许多用户可以扮演许多角色。看起来实体框架仅适用于关系数据库,其中两个实体之间的辅助表用作连接实体。但对于 MongoDB,我有一个存储在用户文档中的角色 ID 集合,我需要为其检索这些角色。
通过 EF 的文档:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Post>()
.HasMany(e => e.Tags)
.WithMany(e => e.Posts)
.UsingEntity(
"PostTag",
l => l.HasOne(typeof(Tag)).WithMany().HasForeignKey("TagsId").HasPrincipalKey(nameof(Tag.Id)),
r => r.HasOne(typeof(Post)).WithMany().HasForeignKey("PostsId").HasPrincipalKey(nameof(Post.Id)),
j => j.HasKey("PostsId", "TagsId"));
}
但这不适用于 MongoDB,因为没有辅助连接表(实体)。
这是我的代码:
public void Configure(EntityTypeBuilder<User> builder)
{
builder
.HasMany(user => user.AssignedRoles)
.WithMany(role => role.Users);
}
如何将ForeignKey定义为ObjectId集合的多对多关系?
不,你不能。基于文档
Foreign Keys
Because MongoDB is a document database, the Entity Framework Core Provider
does not support foreign keys.