I have a table with column type of datetime2 (it was dat开发者_如何转开发etime, but EF as I see works with datetime2).
I have set it as not null and with default value of SYSDATETIME()
. In order to work normaly I have set the property which maps to this column in EF model as Computed
. Now when I am not seting any value in that property I can see notmal record in table, but when I try to set the value from code it ignores it and in all cases set SYSDATETIME()
.
How it is possible to insert default value which is set in DB when no value is in the property in model and value of the property if it is not null and set?
EDIT : Here is sample code
.....
ActionsJournal actionsJournalEntry =
TestFactory.CreateActionEntry(.....);
if (/* some condition */)
{
actionsJournalEntry.CreatedDate = DateTime.Now.AddDay(30); // else it will be null
}
ent.ActionsJournals.AddObject(actionsJournalEntry);
ent.SaveChanges();
....
Short answer: It is not possible without workaround.
You must either set StoreGeneratedPattern.Computed
and always set value in the database or you must set StoreGeneratedPattern.None
and always set value in the application. The difference is that if you set Computed
it never passes your value in update or insert statements whereas None
passes it always even if you don't set it = results in default date which is 1.1.0001 and the reason why you think that EF uses DATETIME2
.
The other problem is design flaw in designer / EF which doesn't allow you setting default value for DateTime
.
Workaround:
Set default value for your date time in custom parameter less constructor of your entity and set StoreGeneratedPattern
to None
:
public partial class ActionsJournal
{
public class ActionsJournal() {
CreatedDate = DateTime.Now.AddDay(30);
}
}
Now you will always have default value for your CreatedDate
unless your application or loading from database overwrite it with another value.
精彩评论