包含與排除類型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 應用程式開發介面Fluent API

您可以使用 fluent 應用程式開發的應用程式開發介面,以排除模型中的型別。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; }
}