简体   繁体   English

EF Core 2.2 中的 SetDefaultValueSql()

[英]SetDefaultValueSql() in EF Core 2.2

I have a solution for auditable entities that works well with EF Core 3.1 and.Net 5.0.我有一个适用于 EF Core 3.1 和 .Net 5.0 的可审计实体的解决方案。 But I need to make it work in an old project with EF Core 2.2.但是我需要让它在一个带有 EF Core 2.2 的旧项目中工作。 The problem is that SetDefaultValueSql() is only available in 3.1 and 5.0.问题是SetDefaultValueSql()仅在 3.1 和 5.0 中可用。

I cannot find any solution to replace property.SetDefaultValueSql("getdate()");我找不到任何解决方案来替换property.SetDefaultValueSql("getdate()"); for the old 2.2 version.对于旧的 2.2 版本。

My code:我的代码:

foreach (var entity in modelBuilder.Model
    .GetEntityTypes()
    .Where(t => t.ClrType.IsSubclassOf(typeof(AuditableEntity)))
)
{
    foreach (var property in entity.GetProperties()
        .Where(p => AuditProperties.Contains(p.Name, StringComparer.InvariantCultureIgnoreCase) 
                     && (p.ClrType == typeof(DateTime) || p.ClrType == typeof(DateTimeOffset)))
    )
    {
        property.SetDefaultValueSql("getdate()");
    }
}

Is there any way to set the Default SQL Value same way in EF Core 2.2?有没有办法在 EF Core 2.2 中以相同的方式设置默认 SQL 值?

You can use this method.您可以使用此方法。

property.HasDefaultValueSql("getdate()")

I test it in ef core 2.x, about more infomation, you can refer to the document .我在 ef core 2.x 中测试过,更多信息可以参考文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM