In previous version of EF, to specify a computed column we would write:
modelBuilder .Entity<Type>() .Property(x => x.ComuptedProperty) .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
This would make sense, because the SQL expression for the computed column is written once in database.
However, after migrating to EF Core, we realized that the syntax should be changed into:
modelBuilder .Entity<Type>() .Property(x => x.ComuptedProperty) .HasComputedColumnSql("SQL Expression should be duplicated here");
This makes sense when we go code first. Because EF Core uses this SQL expression while creating the table.
However, for DB first scenarios this doesn't make sense at all. We tried to leave this parameter empty, and it throws an exception complaining:
The string argument 'sql' cannot be empty
Now things get even worse when you want to have a data access generator. How can we neglect this parameter?
Indeed when using
HasComputedColumnSql you must specfiy the SQL query that will be used for the computed column when generating SQL Script for the associated table. Like you say, this is useful only for Code First approach.
In Database First approach, you can use one of the following methods frol
PropertyBuilder<TProperty> type (description are from XML documentaiton of those methods):
ValueGeneratedOnAdd(): Configures a property to have a value generated only when saving a new entity,unless a non-null, non-temporary value has been set, in which case the set value will be saved instead. The value may be generated by a client-side value generator or may be generated by the database as part of saving the entity.
ValueGeneratedOnAddOrUpdate(): Configures a property to have a value generated when saving a new or existing entity.
ValueGeneratedOnUpdate(): Configures a property to have a value generated when saving an existing entity.
In your case because it's a computed column then the value maybe generated when adding and saving the data so you must use
ValueGeneratedOnAddOrUpdate() method. Again EF documentation say that :
This just lets EF know that values are generated for added or updated entities, it does not guarantee that EF will setup the actual mechanism to generate values.