我发现的所有关于声明默认值的方法都是在 Sql 脚本中生成默认值,而不是在迁移代码中。
我最喜欢的是使用属性:https : //stackoverflow.com/a/34894274/132942
[SqlDefaultValue(DefaultValue = "getutcdate()")]
public DateTime CreatedDateUtc { get; set; }
Run Code Online (Sandbox Code Playgroud)
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class SqlDefaultValueAttribute : Attribute
{
public string DefaultValue { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
modelBuilder.Conventions.Add( new AttributeToColumnAnnotationConvention<SqlDefaultValueAttribute, string>("SqlDefaultValue", (p, attributes) => attributes.Single().DefaultValue));
Run Code Online (Sandbox Code Playgroud)
然后自定义SqlGenerator。但我不喜欢这样,因为我不知道在生成迁移时是否一切都如我所愿。
为此,我像这样修改了MigrationCodeGenerator:https : //stackoverflow.com/a/21024108
public class ExtendedMigrationCodeGenerator : MigrationCodeGenerator
{
public override ScaffoldedMigration Generate(string migrationId, IEnumerable<MigrationOperation> operations, string sourceModel, string targetModel, string @namespace, string className)
{
foreach (MigrationOperation …Run Code Online (Sandbox Code Playgroud) entity-framework default-value ef-code-first entity-framework-6 entity-framework-migrations