Вопрос

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?

Это было полезно?

Решение

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.

Другие советы

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");
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top