ca9163d9
ca9163d9

Reputation: 29159

Set the default DateTimeOffset value?

I have the following model class for entity framework code-first. I want to set the default value current time for CreateTime when creating database table. However, the following code cannot be compiled because

The type 'System.DateTimeOffset' cannot be declared const

Is it a better way to set default value for 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;
}

Upvotes: 2

Views: 4516

Answers (1)

CodeNotFound
CodeNotFound

Reputation: 23200

I think the best way for doing what you need is to override SaveChanges method in your DbContext.

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();
    }
}

Upvotes: 2

Related Questions