0

I need to have a property in my model that will store it's date of creation. It looks like this:

public class User
{
    public User()
    {
        this.DateCreated = DateTime.Now;
    }

    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime DateCreated { get; set; }
}

My question is particularly about the assignment of the DateCreated property in the constructor of the model:

public User()
{
    this.DateCreated = DateTime.Now;
}

It works fine but I'm just wondering whether this approach is correct, as I wasn't able to find anything about it.

Yulian
  • 6,262
  • 10
  • 65
  • 92

2 Answers2

0

It's fine to use constructors to set default values for your entities. Just take care with setting entity references (like this.Group = new Group();) That's something you should never do.

Setting DateCreated is a somewhat special case. You might want to do that when the object is actually saved, for example in an override of DbContext.SaveChanges(). My personal preference is even to do that by database defaults/triggers, so you're independent of local clocks and UTC date/time settings.

Community
  • 1
  • 1
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
0

This is totally correct. Another option is to add the default value into your migrations

AddColumn("dbo.MyTable", "MyDateTime", c => c.DateTime(nullable: false, defaultValueSql: "GETDATE()"));
tenbits
  • 7,568
  • 5
  • 34
  • 53