計算資料行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 APIFluent API

您可以使用 Fluent API,來指定屬性應該對應至計算資料行。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; }
}