EF Codefirst How to create separate table for derived class?

我是研究僧i 提交于 2019-12-10 15:16:27

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/4898453/ef-codefirst-how-to-create-separate-table-for-derived-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!