繼承Inheritance

EF 模型中的繼承用來控制如何將實體類別中的繼承表示在資料庫中。Inheritance in the EF model is used to control how inheritance in the entity classes is represented in the database.

慣例Conventions

依照慣例,決定以決定如何將繼承表示在資料庫中的資料庫提供者。By convention, it is up to the database provider to determine how inheritance will be represented in the database. 請參閱繼承 (關聯式資料庫)針對此與關聯式資料庫提供者的處理方式。See Inheritance (Relational Database) for how this is handled with a relational database provider.

如果模型中明確包含兩個或多個繼承的類型,EF 將只會設定繼承。EF will only setup inheritance if two or more inherited types are explicitly included in the model. EF 會掃描基底或衍生的類型,否則為未包含在模型中。EF will not scan for base or derived types that were not otherwise included in the model. 您可以在模型中包含類型,藉由公開DbSet 繼承階層架構中每個類型。You can include types in the model by exposing a DbSet for each type in the inheritance hierarchy.

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<RssBlog> RssBlogs { get; set; }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

public class RssBlog : Blog
{
    public string RssUrl { get; set; }
}

如果您不想要公開DbSet 對於階層中的一或多個實體,您可以使用 Fluent API,以確保它們會包含在模型。If you don't want to expose a DbSet for one or more entities in the hierarchy, you can use the Fluent API to ensure they are included in the model. 如果您不要依賴慣例,您就可以指定使用明確的基底類型和HasBaseTypeAnd if you don't rely on conventions you can specify the base type explicitly using HasBaseType.

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<RssBlog>().HasBaseType<Blog>();
    }
}

注意

您可以使用.HasBaseType((Type)null)若要從階層中移除的實體類型。You can use .HasBaseType((Type)null) to remove an entity type from the hierarchy.

資料註釋Data Annotations

您無法使用資料註解來設定繼承。You cannot use Data Annotations to configure inheritance.

Fluent APIFluent API

適用於繼承的 Fluent API 取決於您使用的資料庫提供者。The Fluent API for inheritance depends on the database provider you are using. 請參閱繼承 (關聯式資料庫)關聯式資料庫提供者,您可以執行的組態。See Inheritance (Relational Database) for the configuration you can perform for a relational database provider.