2

I have two entities from separate aggregate groups that have a many-to-many relationship:

public class ClientNotificationMethod
    {
        public int ID { get; private set; }
        private ICollection<int> _personIDs;
        //public virtual ICollection<Person> _contactPersonnel { get; set; } //AVOID THIS
    }

The ClientNotificationMethod has a collection of Person IDs, and the Person has a collection of ClientNotificationMethod IDs:

public class Person
    {
        public int ID { get; private set; }
        private ICollection<int> _clientNotificationMethodIDs;
        //public virtual ICollection<ClientNotificationMethod> _clientNotificationMethods { get; set; } //AVOID THIS
    }

From both classes, I commented-out the public virtual ICollection navigation properties, because I'm trying to follow the DDD principle of avoiding overlap between aggregate groups. I also want to prevent eager/lazy-loading lists of entire class objects (I only want the IDs).

When a Person is added/removed from a ClientNotificationMethod, I want EF to update the ICollection<int> properties in each class.

I haven't found any examples of this in my searches. So far, it seems that EF requires navigation properties in both classes to configure a many-to-many relationship. From my understanding of DDD, navigation properties should only be used in this way when the many-to-many relationship is between two objects in the same aggregate group.

Is the many-to-many relationship that I'm aiming for configurable in EF using fluent API?

At one point, I tried configuring a HasMany-WithMany relationship like this:

private void ConfigureClientNotificationMethod(EntityTypeBuilder<ClientNotificationMethod> builder)
{

            builder.ToTable("ClientNotificationMethod");

            builder.HasKey("ID");
    
            builder.Property("ID")
                .IsRequired();
    
            builder.HasMany<Person>().WithMany().UsingEntity<Dictionary<string, object>>("ClientNotificationMethodPersons",
                c => c.HasOne<Person>().WithMany(),
                c => c.HasOne<ClientNotificationMethod>().WithMany());
            
            builder.Property("_personIDs").HasConversion(new JsonValueConverter<ICollection<int>>())
                .HasColumnName("PersonIDs").IsRequired(false);
}

This created a join table, but EF couldn't populate it because I wasn't using any Person or ClientNotificationMethod navigation objects in the classes.

jmagen
  • 41
  • 3

0 Answers0