包含與排除類型Including & Excluding Types

納入模型表示 EF 相關的中繼資料的輸入,然後將嘗試讀取和寫入,或將資料庫的執行個體中的型別。Including a type in the model means that EF has metadata about that type and will attempt to read and write instances from/to the database.

慣例Conventions

依照慣例,會在中公開的型別DbSet在您的內容上的屬性都包含在您的模型。By convention, types that are exposed in DbSet properties on your context are included in your model. 此外,型別中所述OnModelCreating方法也會包含在內。In addition, types that are mentioned in the OnModelCreating method are also included. 最後,以遞迴方式瀏覽探索到的類型的導覽屬性,即可找到任何型別也會包含在模型中。Finally, any types that are found by recursively exploring the navigation properties of discovered types are also included in the model.

例如,下列程式碼清單中會探索所有的三種類型:For example, in the following code listing all three types are discovered:

  • Blog 因為它會公開在DbSet內容上的屬性Blog because it is exposed in a DbSet property on the context

  • Post 因為它透過探索Blog.Posts導覽屬性Post because it is discovered via the Blog.Posts navigation property

  • AuditEntry 因為它被提及中 OnModelCreatingAuditEntry because it is mentioned in OnModelCreating

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<AuditEntry>();
    }
}

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

    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public Blog Blog { get; set; }
}

public class AuditEntry
{
    public int AuditEntryId { get; set; }
    public string Username { get; set; }
    public string Action { get; set; }
}

資料註釋Data Annotations

若要從模型中排除的型別,您可以使用資料註解。You can use Data Annotations to exclude a type from the model.

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

    public BlogMetadata Metadata { get; set; }
}

[NotMapped]
public class BlogMetadata
{
    public DateTime LoadedFromDatabase { get; set; }
}

Fluent APIFluent API

您可以使用 Fluent API,若要從模型中排除的型別。You can use the Fluent API to exclude a type from the model.

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Ignore<BlogMetadata>();
    }
}

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

    public BlogMetadata Metadata { get; set; }
}

public class BlogMetadata
{
    public DateTime LoadedFromDatabase { get; set; }
}