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.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
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.
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:
Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute
You can also handle the
SavingChanges
event on your context, and add default values there, but that only happens when you actually callSaveChanges()
, not when the object is created.