For example I have two simple string properties inside my model:
public class Model
{
public string BaseString {get;set;}
public string MyValue {get;set;}
}
Inside my OnModelCreating:
modelBuilder
.Entity<Model>()
.Property(f => f.MyValue)
.ValueGeneratedOnAdd()
.HasDefaultValueSQL(//insert first letter of inserted BaseString property + something else);
Is something like that possible? Or can default values only be constants? What is the correct approach?
No, it's not possible. The following was the configuration tested;
modelBuilder
.Entity<Model>()
.Property(f => f.MyValue)
.HasDefaultValueSQL("CONCAT(SUBSTRING(BaseString, 0, 1), \'something else\')");
And the following migration generated;
migrationBuilder.CreateTable(
name: "Test",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
BaseString = table.Column<string>(nullable: true),
MyValue = table.Column<string>(nullable: true, defaultValueSql: "CONCAT(SUBSTRING(BaseString, 0, 1), 'something else')")
},
constraints: table =>
{
table.PrimaryKey("PK_Test", x => x.Id);
});
Yet, when tried to apply the migration, the following error generated. And the error is quite descriptive about the supporting configurations.
The name "BaseString" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.