The Fluent API HasComputedColumnSql Method

The Entity Framework Core Fluent API HasComputedColumnSql method is used to specify that the property should map to a computed column. The method takes a string indicating the expression used to generate the default value for a database column.

In the following example, the LastModified property of the Contact entity is mapped to a computed column. The value of the column is generated by the database's GetUtcDate() method whenever the row is created or updated:

public class Contact
    public int ContactId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime LastModified { get; set; }

public clas SampleContext : DbContext
    public DbSet<Contact> Contacts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
            .Propery(p => p.LastModified)

The next example is taken from the AdventureWorks sample database. It shows the SalesOrderNumber property of the SalesOrderHeader entity being generated by concatenating "SO" with the SalesOrderId value, or adding the text "*** ERROR ***" if the SalesOrderId is null:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    .Property(e => e.SalesOrderNumber)
    .HasComputedColumnSql("isnull(N'SO'+CONVERT([nvarchar](23),[SalesOrderID]),N'*** ERROR ***')");

Data Annotations

It is not possible to configure computed columns using data annotations.

Last updated: 14/03/2017 16:33:44
Proficiency Level: Beginner