EF Core HasComputedColumnSql

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:

language-csharp
|
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 class SampleContext : DbContext
{
    public DbSet<Contact> Contacts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Contact>()
            .Propery(p => p.LastModified)
            .HasComputedColumnSql("GetUtcDate()");
    }
}

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:

language-csharp
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<SalesOrderHeader>()
    .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.


Date Modified: 2023-08-27
Author:

Edit this page in GitHub

Got any EF Core Question?