Search code examples
entity-frameworkentity-framework-core.net-6.0

can you have many to many and one to many without Collection properties on the other end in Entity Framework


this is my current working solution:

public class Person
{
    public ICollection<Foo> Foos { get; set; }
    public Foo BonusFoo { get; set; }
}

public class Foo
{        
    public ICollection<Person> Persons { get; set; }
    public ICollection<Person> Persons2 { get; set; }
}

public class MemContext : DbContext
{
    ...
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>()
            .HasMany(b => b.Foos)
            .WithMany(o => o.Persons);

        modelBuilder.Entity<Person>()
            .HasOne(o => o.BonusFoo)
            .WithMany(o => o.Persons2);

        base.OnModelCreating(modelBuilder);
    }
}

I will never actually need to access in code Foo.Persons or Foo.Persons2, is it possible to have the same configuration but without these 2 properties on the Foo ?


Solution

  • Update (EF Core 7.0+):

    EF Core 7 added support for Unidirectional many-to-many relationships, so since then the answer for all type of relationships is positive.

    Original:

    The answer for one-to-many is positive (yes). Remove Persons2 property from Foo and use WithMany w/o passing navigation property (since there isn't):

    modelBuilder.Entity<Person>()
        .HasOne(o => o.BonusFoo)
        .WithMany(); // <--
    

    The answer for many-to-many is negative(no) currently (EF Core 5, 6) as explained at the beginning of the Many-to-many documentation:

    Many-to-many relationships require a collection navigation property on both sides.

    It will be possible though in the upcoming EF Core 7 - Support unidirectional many-to-many relationships through shadow navigations #3864.

    Until then, keep the Person.Foos and Foo.Persons collection properties in the model (even if you "don't need" the later) and the existing fluent configuration.