計算資料行Computed Columns

注意

本節中的設定是一般適用於關聯式資料庫。The configuration in this section is applicable to relational databases in general. 當您安裝的關聯式資料庫提供者,如下所示的擴充方法會變成可用 (因為共用Microsoft.EntityFrameworkCore.Relational封裝)。The extension methods shown here will become available when you install a relational database provider (due to the shared Microsoft.EntityFrameworkCore.Relational package).

計算資料行是計算其值在資料庫中的資料行。A computed column is a column whose value is calculated in the database. 計算資料行可以使用資料表中的其他資料行,來計算其值。A computed column can use other columns in the table to calculate its value.

慣例Conventions

依照慣例,不會在模型中建立計算資料行。By convention, computed columns are not created in the model.

資料註釋Data Annotations

計算資料行不可以設定使用資料註解。Computed columns can not be configured with Data Annotations.

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

您可以使用 fluent 應用程式開發的應用程式開發介面來指定屬性應該為計算資料行對應。You can use the Fluent API to specify that a property should map to a computed column.

class MyContext : DbContext
{
    public DbSet<Person> People { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>()
            .Property(p => p.DisplayName)
            .HasComputedColumnSql("[LastName] + ', ' + [FirstName]");
    }
}

public class Person
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string DisplayName { get; set; }
}