Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 894
nttakr Avatar asked Feb 04 '11 13:02

nttakr


Video Answer


1 Answers

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");
    });            
}
like image 98
hazimdikenli Avatar answered Oct 12 '22 23:10

hazimdikenli