如何解决如何在实体框架代码第一个迁移文件中生成默认的sql值
我们已经定义了一个基类
public class BaseSchema
{
[Key]
[ScaffoldColumn(false)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public bool IsDeleted { get; set; }
public DateTime PerformedOn { get; set; }
}
从这个 Base 模式派生所有其他类。示例类是
public class HoodAudit : BaseSchema{}
在datacontext类中添加HoodAudit
并运行迁移后,生成的迁移文件为
CreateTable(
"dbo.HoodAudits",c => new
{
Id = c.Int(nullable: false,identity: true),//Other properties
IsDeleted = c.Boolean(nullable: false),PerformedOn = c.DateTime(nullable: false),},
我们要将 PerformedOn
设为 PerformedOn = c.DateTime(nullable: false,defaultValueSql: "GETDATE()"),
并将 IsDeleted
设为 IsDeleted = c.Boolean(nullable: false,defaultValueSql: "0"),
有什么办法可以做到这一点吗? 当我们从 BaseSchema 派生所有其他类时,如果您建议任何适用于其所有派生类的通用方法,那就太好了。 谢谢!
解决方法
据我所知,在实体属性上没有指定默认数据库值(SQL 计算或其他方式)的属性,相反,您需要将信息添加到 DbContext 类的“OnModelCreating”方法中,并且它'将使用该信息进行迁移。您会发现 OnModelCreating 有许多强大的功能是您无法使用属性实现的...
这里有两组示例,一组用于 EF 6,一组用于 EF Core。
EF 6
中的单个实体属性配置[
{"genderid":1515,"modnameid":1515},{"genderid":1516,"modnameid":1516},{"genderid":1513,"modnameid":1514}
]
要对 EF 6 中从 public class MyDbContext : Microsoft.EntityFrameworkCore.DbContext
{
protected override void OnModelCreating(DbModelBuilder builder)
{
base.OnModelCreating(builder);
modelBuilder.Entity<MyInheritedEntityType>()
.Property(p => p.PerformedOn)
.HasColumnAnnotation("SqlDefaultValue","getDate()");
}
}
继承的所有实体执行此操作,需要三个步骤:
- 创建一个属性来标记需要在基类中配置的属性:
BaseSchema
- 将该特性应用于您希望默认为
/// <summary> /// Simply an empty attribute that specifies the field should be defaulted to GetDate() in DB. /// </summary> [System.AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,AllowMultiple = false,Inherited = true)] class DefaultToNowAttribute: Attribute { }
的任何DateTime
属性(包括在基类中)
GetDate()
- 在
class BaseSchema { [Key] [ScaffoldColumn(false)] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public bool IsDeleted { get; set; } [DefaultToNow] public DateTime PerformedOn { get; set; } }
中使用以下内容:
OnModelCreating
EF Core 5 中的单个实体示例:
modelBuilder.Properties<DateTime>()
.Where(x => x.CustomAttributes.Any(y => y.AttributeType == typeof(DefaultToNowAttribute)))
.Configure(x => x.HasColumnAnnotation("SqlDefaultValue","getDate()"));
要对从 EF Core 5 中的 public class MyDbContext : Microsoft.EntityFrameworkCore.DbContext
{
protected override void OnModelCreating(DbModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<HoodAudits>(ha =>
ha.Property(p => p.PerformedOn).HasDefaultValueSql("GETDATE()"));
}
}
继承的所有实体执行此操作,您可以在 BaseSchema
中使用以下内容:
OnModelCreating
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。