c# - 设置默认的 DateTimeOffset 值?

标签 c# entity-framework entity-framework-5

我有以下用于 Entity Framework 代码优先的模型类。我想在创建数据库表时为CreateTime设置默认值当前时间。但是,以下代码无法编译,因为

The type 'System.DateTimeOffset' cannot be declared const

DateTimeOffset 设置默认值是否是更好的方法?

public class MyClass
{
    public int Id { get; set; }
    public string Title { get; set; }
    [DefaultValue(now)]
    public DateTimeOffset CreateTime 
    { 
        get { return _createTime; } 
        set { _createTime = value; } 
    }

    private const DateTimeOffset now = DateTimeOffset.Now;
    private DateTimeOffset _createTime = now;
}

最佳答案

我认为完成您需要的操作的最佳方法是重写 DbContext 中的 SaveChanges 方法。

public class MyDbContext : DbContext
{
    public override int SaveChanges()
    {
        foreach (var entry in this.ChangeTracker.Entries<MyClass>().Where(x => x.State == EntityState.Added))
        {
            entry.Entity.CreateTime = DateTimeOffset.Now;
        }

        return base.SaveChanges();
    }
}

关于c# - 设置默认的 DateTimeOffset 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20452372/

相关文章:

c# - 何时何地使用 GetType() 或 typeof()?

c# - 创建螺旋星系需要数学指导

database - 如何获取自引用对象中最顶层的父级

oracle - 您的项目引用了最新版本的 Entity Framework ... - 错误

c# - 无法像游戏一样在 2D 太空入侵者中发射激光

c# - TiffBitmapEncoder,内存错误导致 C#/WPF 中内存不足异常

entity-framework - 如何使用 Entity Framework 在Sql Server Express中获取下一个序列号?

entity-framework - Entity Framework HierarchyId 解决方法

c# - Linq to Entities 4.1 - 组查询强制排序

c# - 无法在类库中为 Entity Framework 启用迁移