Search code examples
c#entity-frameworkef-fluent-api

Entity Framework Fluent API - Map Property to Specific Table


I would like to create internal mapping of navigation property to specific table using EF's fluent API.

Meaning - Same type is mapped to different tables according to parent type

(see code below) Thank you!

public record Entity1
{
   public long Id { get; set;}
   public IEnumerable<Identifier> Ids { get; set; } //Map to map to table 'Entity1_Ids'
}

public record Entity2
{
   public long Id { get; set;}
   public Identifier Ids { get; set; } //Map to map to table 'Entity2_Ids'
}

public record Identifier
{
   public long Id { get; set;}
   public string? Type { get; set; }
   public string? Value { get; set; }
}

Solution

  • You can do this with Owned Entity Types.

    eg

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    
        modelBuilder.Entity<Entity1>().OwnsMany(e => e.Ids).ToTable("Entity1_Ids");
        modelBuilder.Entity<Entity2>().OwnsOne(e => e.Ids).ToTable("Entity2_Ids");
    
    }