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:
I need to map this relation to a one-to-many domain entities relation as bellow:
How can I map this using Fluent API?
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");
});
}
}