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

54 Views Asked by At

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?

2

There are 2 best solutions below

1
D A On BEST ANSWER

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.
1
Kamil On

You can simulate it as well:

public class X 
{
  public Guid Id {get;set;}
  public string Name {get;set;}
}

public class Y 
{
  public Guid Id {get;set;}
  public int SomethingElse {get;set;}
}

public class XY
{
  public Guid XId {get;set;}
  public X x {get;set;}
  public Guid YId {get;set;}
  public Y y {get;set;}
}

And then in repository create function to manage that.