[英]Entity framework: StoreGeneratedPattern=“Computed” property
I have a DateTime
property. 我有一个
DateTime
属性。 I need this property's default value to be DateTime.Now
. 我需要此属性的默认值为
DateTime.Now
。 And then I found out that you can specify an attribute StoreGeneratedPattern="Computed"
and set it to (getdate())
in SQL. 然后我发现你可以指定一个属性
StoreGeneratedPattern="Computed"
并在SQL中将其设置为(getdate())
。 This works successfully. 这成功了。 But I can't change this property in code.
但我无法在代码中更改此属性。 Sometimes I need to change this property to any DateTime value.
有时我需要将此属性更改为任何DateTime值。 But my changes are not saved.
但是我的更改没有保存。
Setting this property to Computed is telling EF that you cannot set the value directly. 将此属性设置为Computed会告诉EF您无法直接设置该值。 How could you?
你怎么能? This property exists for the sake of computed columns, which by definition are not saved back to the database.
此属性存在于计算列中,根据定义,列不会保存回数据库。
Unfortunately, EF's "Default Value" property can only be set to values known at compile-time, and so not DateTime.Now
不幸的是,EF的“默认值”属性只能设置为编译时已知的值,因此不能设置为
DateTime.Now
This link provides a decent workaround: 此链接提供了一个不错的解决方法:
Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute 将DateTime属性的默认值设置为System.ComponentModel内的DateTime.Now默认值Attrbute
You can also handle the SavingChanges
event on your context, and add default values there, but that only happens when you actually call SaveChanges()
, not when the object is created. 您还可以在上下文中处理
SavingChanges
事件,并在那里添加默认值,但这只会在您实际调用SaveChanges()
,而不是在创建对象时发生。
partial void OnContextCreated() {
this.SavingChanges += new EventHandler(AccrualTrackingEntities_SavingChanges);
}
void AccrualTrackingEntities_SavingChanges(object sender, EventArgs e) {
List<Invoice> Invoices = this.ObjectStateManager
.GetObjectStateEntries(System.Data.EntityState.Added | System.Data.EntityState.Modified)
.Select(entry => entry.Entity)
.OfType<Invoice>().ToList();
foreach(Invoice I in Invoices)
if (I.EntityState == System.Data.EntityState.Added) {
//set default values
} else {
//?? whatever
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.