EF Core: Is it possible to have a dynamic defaultValue? E.g. depending on another value?

entity-framework entity-framework-core

Question

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?

1
1
7/15/2019 5:37:45 PM

Accepted Answer

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.

1
7/15/2019 6:33:51 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow