简体   繁体   中英

EF Codefirst How to create separate table for derived class?

I have objects in their own tables using EF Codefirst. Now I try to produce an "archive" for changed objects living in separate tables for each of those 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 the Model it does NOT include the properties of Person in Person_Archive :-( Even if I add:

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

EF still does not repeat the properties from the derived class.

Has anyone an idea how to achieve that?

Thanks! Andreas

yeah, you need to call something like MapInheritedProperties method to do that.

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");
    });            
}

Adding here for documentation sake...if you are using EntityTypeConfiguration to keep your data model from having EF specific references then you need to use Map property of EntityTypeConfiguration like below.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM