问题
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