实体框架:StoreGeneratedPattern="Computed"财产 [英] Entity framework: StoreGeneratedPattern="Computed" property
问题描述
我有一个 DateTime
属性.我需要此属性的默认值为 DateTime.Now
.然后我发现您可以在 SQL 中指定一个属性 StoreGeneratedPattern="Computed"
并将其设置为 (getdate())
.这工作成功.但我无法在代码中更改此属性.有时我需要将此属性更改为任何 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.
推荐答案
将此属性设置为 Computed 是告诉 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.
不幸的是,EF 的默认值"属性只能设置为编译时已知的值,因此不能设置 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:
设置一个DateTime属性的默认值到DateTime.Now里面的System.ComponentModel默认值属性
您还可以在您的上下文中处理 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="Computed"财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!