开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜