EF Core (< 5.0) HasComputedColumnSql - computed on Insert/Update or each query on SQL Server / AzureSQL?

Viewed 4431

Note: this question is referencing an old EF Core issue. See this answer for a discussion relevant to EF Core 5.

I'm seeing conflicting information about this. LearnEntityFrameworkCore.com says you can write

.HasComputedColumnSql("GetUtcDate()");

The value of the column is generated by the database's GetUtcDate() method whenever the row is created or updated

However, in the technet documentation for computed columns on SQL Server it says:

Their values are recalculated every time they are referenced in a query.

2 Answers

The two documentation you referenced are correct. Each is talking about different methods. There are several overloads for this method. You can check this over here (search for "HasComputedColumnSql" in the browser).

If there are triggers in the database that define values for this column, you will use the HasComputedColumnSql() implementation.

If you want to store a computed value on the property, but don't want it to persist in the table, you will use the HasComputedColumnSql("SomeFunction()") implementation.

If you want to store the value in a column, you will use the implementation HasComputedColumnSql("SomeFunction()", stored: true).

Related