How do I get Entity Framework 4.3 Code First to map a subclass using Table Per Type (TPT)?

▼魔方 西西 提交于 2019-12-23 02:57:06

问题


I'm using EF 4.3 Code First and automatic migrations. I have the following 3 classes:

public class BaseUser
{
    [Key]
    [MaxLength(50)]
    public string Username { get; set; }

    [MaxLength(200)]
    public string Password { get; set; }
}

public class AdminUser : BaseUser
{
    public int SettingsFlag { get; set; }
}

public class RegularUser : BaseUser
{
    public DateTime LastLogin { get; set; }
    public DateTime LastSummary { get; set; }

    [MaxLength(100)]
    public string Email { get; set; }

    public int CompanyID { get; set; }
    public int ContactID { get; set; }
}

When I run update-database on this, it uses TPH (Table-Per-Hierarchy) to make a single table for all 3, merging all of these properties together and adding a Discriminator column.

How do I ensure I end up with 3 tables?


回答1:


The trick turns out to be pretty simple - explicitly name each table and EF figures it out on its own, including creating the FK relationship:

[Table("BaseUser")]
public class BaseUser
...

[Table("AdminUser")]
public class AdminUser : BaseUser
...

[Table("RegularUser")]
public class RegularUser : BaseUser

This gets me the 3 tables with a one-to-one FK join as intended.




回答2:


If you prefer fluent API, then you can create a TPT mapping by using ToTable() method:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<AdminUser>().ToTable("AdminUser");
    modelBuilder.Entity<RegularUser>().ToTable("RegularUser");
}


来源:https://stackoverflow.com/questions/9511021/how-do-i-get-entity-framework-4-3-code-first-to-map-a-subclass-using-table-per-t

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