Search code examples
c#.netmongodbentity-frameworkmany-to-many

How to define many-to-many relationship using Entity Framework for MongoDB


I have two collections in MongoDB with many-to-many relationship. Many users can be cast in many roles. It looks like Entity Framework is adapted only for relational databases, where an helper table between two entities is used as a join entity. But in the case of MongoDB, I have a collection of role IDs stored in the User document for which I need to retrieve these roles.

By the documentation of the 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"));
}

But this is not applicable for MongoDB, because there is no helper joining table (entity).

Here is my code:

public void Configure(EntityTypeBuilder<User> builder)
{
    builder
        .HasMany(user => user.AssignedRoles)
        .WithMany(role => role.Users);
}

How do I define a many-to-many relationship with ForeignKey as a collection of ObjectId?


Solution

  • No, you can't. Based on the documentation

    Foreign Keys
    Because MongoDB is a document database, the Entity Framework Core Provider 
    does not support foreign keys.