简体   繁体   中英

Is it correct to assign values in a model's constructor in Entity Framework's Code-First approach?

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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