efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Question: How does HasComputedColumnSql work?

Open dealdiane opened this issue 10 years ago • 6 comments

Using the example given in http://ef.readthedocs.io/en/latest/modeling/relational/computed-columns.html

I would've expected the projected SQL to be: SELECT PersonId, FirstName, LastName, LastName + ', ' + FirstName as DisplayName FROM Persons

but the actual projected SQL is: SELECT PersonId, FirstName, LastName, DisplayName FROM Persons

I hope I am not being dumb here. I'm just completely blank at the moment. Why do we even need to pass a SQL statement argument in the HasComputedColumnSql method if it's not used?

EDIT: Or is it only used for migrations?

dealdiane avatar Oct 11 '16 21:10 dealdiane

It works the same way as SQL server's computed columns. You specify computed value for a column and that column value gets computed on insert or updated on edit automatically (you can't change it by hand).

So in your case projected sql is correct, because DisplayName is already calculated and exists in the database as a column with value LastName + ', ' + FirstName.

It is used in migration code to create that kind of column, so you wouldn't have to fallback to altering tables with raw sql.

Muchiachio avatar Oct 12 '16 14:10 Muchiachio

In addition to being used in Migrations, calling HasComputedColumnSql tells the Update pipeline not to save any values for that column and to read back any new value for it after updating the row.

bricelam avatar Oct 12 '16 16:10 bricelam

@bricelam it doesn't appear to be the case. I'm using 2.0.0 and EF core tries to update the property I defined with HasComputedColumnSql . I had to add [DatabaseGenerated(DatabaseGeneratedOption.Computed)] to the property to stop EF from trying to update the property. Is that a bug? If not, at least the docs should make that clear.

clement911 avatar Dec 02 '17 04:12 clement911

Yes. If you can boil it down to a simple repro, please submit a new issue.

bricelam avatar Dec 02 '17 19:12 bricelam

The method HasComputedColumnSql does not work as developers might expected. Official example https://docs.microsoft.com/en-us/ef/core/modeling/relational/computed-columns is wrong.

art13g avatar May 30 '18 11:05 art13g

@art13g - Please file a new issue with repro steps, your expectations and current behavior.

smitpatel avatar May 30 '18 18:05 smitpatel