[英]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: 我的问题特别是关于在模型的构造函数中DateCreated属性的分配:
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 . 只需注意设置实体引用(例如this.Group = new Group();
),这是您永远都不应做的事情 。
Setting DateCreated
is a somewhat special case. 设置DateCreated
是一种特殊情况。 You might want to do that when the object is actually saved, for example in an override of DbContext.SaveChanges()
. 您可能想要在实际保存对象时执行此操作,例如在重写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. 我个人的喜好甚至是通过数据库默认值/触发器来做到这一点,因此您独立于本地时钟和UTC日期/时间设置。
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()"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.