EF Codefirst How to create a separate table for a derived class?

I have objects in their own tables using EF Codefirst. Now I am trying to create an โ€œarchiveโ€ for the modified objects living in separate tables for each of these objects.

For instance:

public class Person  
{  
    [Key]
    public virtual Guid Id { get; set; }

    [Required]
    public string Name { get; set; }
}

public class Person_Archive : Person 
{
    [Key]
    [Columnn( Order = 1 )]
    public override Guid Id { get; set; }

    [Key]
    [Columnn( Order = 2 )]
    public DateTime ChangedAt { get; set; }

    public string ChangedBy { get; set; }
}

When I let EF create a model, it does NOT include Person properties in Person_Archive :-( Even if I add:

modelBuilder.Entity<Person>().ToTable( "Person" );
modelBuilder.Entity<Person_Archiv>().ToTable( "Person_Archiv" );

EF still does not repeat properties from a derived class.

Does anyone know how to achieve this?

Thank! Andreas

+3
source share
2 answers

Yes, you need to call something like a method MapInheritedPropertiesto do this.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Person>().Map(m =>
    {
        m.MapInheritedProperties();
        m.ToTable("People");
    });

    modelBuilder.Entity<Person_Archieve>().Map(m =>
    {
        m.MapInheritedProperties();
        m.ToTable("People_Archieve");
    });            
}
+3
source

... EntityTypeConfiguration, EF, Map EntityTypeConfiguration, .

public class ArchivedPersonConfiguration : EntityTypeConfiguration<Person_Archieve>
{
    Map(m => m.MapInheritedProperties()).ToTable("People_Archieve");
}
0

Source: https://habr.com/ru/post/1789982/


All Articles