Search code examples
.netmany-to-manyentity-framework-6one-to-manyef-fluent-api

Mapping from many-to-many in database to one-to-many in domain


I have a mapping challange in Entity Framework.

In the database I have a many-to-many relation between two tables with a intermediate table with the PK of the both as bellow:

Many-To-Many with Dependents intermediated table

I need to map this relation to a one-to-many domain entities relation as bellow:

One-To-Many entities relation

How can I map this using Fluent API?


Solution

  • You can use a navigation property and set the Dependents table in the model:

    public class Title
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    
        public virtual ICollection<Person> Dependents { get; set; }
    }
    
    public class Person
    {
        public int Id { get; set; }
    
        public string Name { get; set; }
    }
    
    public class MyContext : DbContext
    {
        public DbSet<Title> Titles { get; set; }
        public DbSet<Person> People { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.Entity<Title>()
                .HasMany<Person>(t => t.Dependents)
                .WithMany()
                .Map(d =>
                {
                    d.MapLeftKey("Title_Id");
                    d.MapRightKey("Person_Id");
                    d.ToTable("Dependents");
                });
        }
    }