包含與排除內容Including & Excluding Properties

包含模型中的屬性,表示 EF 具有該屬性的相關中繼資料,並將嘗試讀取和寫入自/至資料庫的值。Including a property in the model means that EF has metadata about that property and will attempt to read and write values from/to the database.

慣例Conventions

依照慣例,公用屬性 getter 和 setter 將會包含在模型中。By convention, public properties with a getter and a setter will be included in the model.

資料註釋Data Annotations

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

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

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

關於 fluent 應用程式開發介面Fluent API

若要從模型中排除屬性,您可以使用 fluent 應用程式開發的應用程式開發介面。You can use the Fluent API to exclude a property from the model.

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Ignore(b => b.LoadedFromDatabase);
    }
}

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

    public DateTime LoadedFromDatabase { get; set; }
}