How do I get this column as similar to a PERSISTED COMPUTED column in the database?
My current attempt (it loads all CompCol rows with null in seed) :
public class Call
{
public Call()
{
}
[Key]
public int Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public string CompCol
{
get
{
return "ABC-" + Convert.ToString(Id).PadLeft(5, '0');
}
protected set {}
}
}
The solution I found was to :
Make sure auto migrations are turned off. This is so that VS will generate a script (fluent api code) for us to further customise instead of just running it. So in the configuration class :
Add the field to the class and set it as computed like so, the setter is private because we obviously cannot write to a computed field :
Then do an
add-migration [xyz-name]in the Package Manager Console to generate the migration code, which will appear under the migrations folder with the given name.Inside the migration comment out the code in
Up()and add custom SQL like so :Do an
update-databasein the PM and it should add the computed column properly.FURTHER NOTES : If you get the formula wrong then you will have to revert back the migration by doing an
update-database -targetMigration: [name of migration to go back to]then do anotheradd-migration nameand amend your formula there, finishing off with update-database. There may be a better way but this is what I found and used.I did not however find a way to make the field persisted yet.