Reputation: 109
I'm trying to initialze the CreatedAt and Guid value the first time a record is created via Entity Framework. But when performing an update using the same model, I don't want to overwrite that value. (As it is a timestamp for creation)
This is what I have currently:
public EntityBase()
{
if(this.CreatedAt == null)
this.CreatedAt = DateTimeOffset.Now;
this.UUId = new Guid();
this.UpdatedAt = DateTimeOffset.Now;
}
Whenever I create an instance of this model the constructor will be invoked and a new DateCreated value. Would this be a valid way?
Upvotes: 0
Views: 1715
Reputation: 1134
Edit:
Or in constructor:
if (this.CreatedAt == default(DateTimeOffset))
{
this.CreatedAt = DateTimeOffset.Now;
}
Upvotes: 0
Reputation: 239300
With C# 7, just use an auto prop with a default:
public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow;
That will set it to DateTimeOffset.UtcNow
only if it's null.
Upvotes: 0
Reputation: 2887
You can simply remove the "if" from your constructor and leave it as is - assigning default values to the fields. For a newly created entity, those will be used as default. When your application will set some values and store it to some storage and at a later time try to retrieve it, the persisted values will be restored, because the data layer will try to set those properties to their persisted values, and will call the property setters, no matter what the value is.
public EntityBase()
{
this.CreatedAt = DateTimeOffset.Now;
this.UUId = new Guid();
this.UpdatedAt = this.CreatedAt;
}
When updating a record, that record would be already retrieved, hence have non-default values for the creation date.
Also note, how I've set the "UpdatedAt" to the same "CreatedAt" - to not get a different time value (there can be minor difference in your example) - a bit unrelated tip.
Upvotes: 2