包含與排除屬性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 APIFluent API

您可以使用 Fluent API,若要從模型中排除的屬性。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; }
}