首页 > 解决方案 > EF Core:是否可以有一个动态的 defaultValue?例如,取决于另一个值?

问题描述

例如,我的模型中有两个简单的字符串属性:

public class Model
{
    public string BaseString {get;set;}
    public string MyValue {get;set;}
}

在我的 OnModelCreating 中:

modelBuilder
.Entity<Model>()
.Property(f => f.MyValue)
.ValueGeneratedOnAdd()
.HasDefaultValueSQL(//insert first letter of inserted BaseString property + something else);

这样的事情可能吗?或者默认值只能是常量?什么是正确的方法?

标签: entity-frameworkentity-framework-core

解决方案


不,这是不可能的。以下是测试的配置;

modelBuilder
.Entity<Model>()
.Property(f => f.MyValue)
.HasDefaultValueSQL("CONCAT(SUBSTRING(BaseString, 0, 1), \'something else\')");

并产生了以下迁移;

  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);
                });

然而,当尝试应用迁移时,会产生以下错误。并且该错误对支持配置的描述性很强。

在此上下文中不允许使用名称“BaseString”。有效表达式是常量、常量表达式和(在某些情况下)变量。不允许使用列名。


推荐阅读