entity-framework - 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);
这样的事情可能吗?或者默认值只能是常量?什么是正确的方法?
解决方案
不,这是不可能的。以下是测试的配置;
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”。有效表达式是常量、常量表达式和(在某些情况下)变量。不允许使用列名。
推荐阅读
- vue.js - 在操作中访问状态显示为空状态
- rundeck - Rundeck SSH 执行
- android - Android 中的促销代码、实施和验证
- vba - 即使我已经做出了所有必要的声明并设置了我的变量,也会出现编译错误('需要对象)
- python - 根据第一个空格拆分列中的文本,将唯一值放入列表中
- oop - 如何在 f# 中引用同一类中的方法?
- microsoft-graph-api - 在 O365 & Exchange 的混合设置中如何区分用户?
- neo4j - 是否可以处理从 Airflow Task 内部关闭的任务?
- amazon-web-services - 如何将旧 S3 存储桶中的 Terraform 状态移动到新的 S3 存储桶?
- python - Django 使用 if 块扩展哪个模板