实体框架:StoreGeneratedPattern ="已计算"属性 [英] Entity framework: StoreGeneratedPattern="Computed" property
问题描述
我有一个的DateTime
属性。我需要这个属性的默认值是 DateTime.Now
。然后我发现,你可以指定一个属性 StoreGeneratedPattern =计算
键,将其设置为(GETDATE())
在SQL。这成功地运作。但我不能改变code此属性。有时候,我需要这个属性更改为任何DateTime值。但我不保存更改。
I have a DateTime
property. I need this property's default value to be DateTime.Now
. And then I found out that you can specify an attribute StoreGeneratedPattern="Computed"
and set it to (getdate())
in SQL. This works successfully. But I can't change this property in code. Sometimes I need to change this property to any DateTime value. But my changes are not saved.
推荐答案
此属性设置为已计算告诉EF你的无法的值直接设置。你怎么能?此属性存在计算列的缘故,它通过定义不保存到数据库中。
Setting this property to Computed is telling EF that you cannot set the value directly. How could you? This property exists for the sake of computed columns, which by definition are not saved back to the database.
不幸的是,英孚的默认值属性只能设置在编译时已知值,所以不能 DateTime.Now
Unfortunately, EF's "Default Value" property can only be set to values known at compile-time, and so not DateTime.Now
此链接提供一个体面的解决办法:
This link provides a decent workaround:
<一个href=\"http://stackoverflow.com/questions/691035/setting-the-default-value-of-a-datetime-property-to-datetime-now-inside-the-syste\">Setting一个DateTime属性的默认System.ComponentModel里面的默认值DateTime.Now值Attrbute
您还可以处理 SavingChanges
事件对你的背景,并添加默认值在那里,但是当你真正调用只发生的SaveChanges()
,而不是在创建对象时。
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.
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
}
}
这篇关于实体框架:StoreGeneratedPattern =&QUOT;已计算&QUOT;属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!