1 year ago

#69110

test-img

Stefan Golubović

Map entity to multiple tables with Entity Framework Core

I'm trying to implement Temporal Normal Form using Entity Framework Core.

Consider having following entity:

public class Employee
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public DateTimeOffset Created { get; set; }

    public DateTimeOffset Deleted { get; set; }

    public DateTimeOffset Effective { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    // other properties
}

Next step would be to split static and temporally-sensitive properties into two tables. Static properties, as name suggests, are properties that would never change once they are inserted (except Deleted property which soft-deletes entity, but let's not focus on that). On the other hand, temporally-sensitive properties are properties which may and probably will change over time. Every change is represented as a record in *Versions table.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Employee>()
        .Map(m =>
            {
                m.Properties(e => new { e.Id, e.Created, e.Deleted, e.FirstName }); // static properties
                m.HasKey(e => e.Id);
                m.ToTable("Employees");
            })
        .Map(m =>
            {
                m.Properties(e => new { e.Id, e.Effective, e.LastName }); // temporally-sensitive properties
                m.HasKey(e => new { e.Id, e.Effective });
                m.ToTable("EmployeeVersions");
            });
}

I've noticed that Entity Framework has this ability to split entities into multiple tables using Map method, but I can't find anything similar in EF Core.

Is it possible (and how) to split entities into multiple table using EF Core?

c#

entity-framework-core

ef-core-6.0

0 Answers

Your Answer

Accepted video resources