In my SQL Server database schema I have a data table with a date field that contains a default value of
CONVERT(VARCHAR(10), GETDATE(), 111)
<
I had a similar problem using RIA Services with the Entity Framework. I was not able to set the value in the default constructor on the client side because the entity classes that are generated there already have an empty default constructor.
The solution that I used was to implement the OnCreated partial method for the entity on the client by setting the required default value.
This is really unfortunate. The answers referencing StoreGeneratedPattern
are not a true solution, that doesn't allow you to ever set the value.
All the team would have to do is something like this:
[Required]
[DefaultValue] // suggested attribute, whatever you want to call it
public DateTime Created { get; set; }
If a field is marked DefaultValue, then at EF's SQL generation time, properties with this attribute get checked if field == default(DateTime)
, if so, then simply omit that column from the generated code.
The date field can be mapped to DateTime? only if the column is nullable in the database.
Create a partial class for your EntityObject, add a default constructor, and set default values in it.
public partial class YourDBObject
{
public YourDBObject()
{
this._DateField = DateTime.Now;
}
}
You can use a database trigger, which, on insertion, checks if the inserted value is DateTime.MinValue (01.01.0001) and replaces it with the calculated value you desire. This MSDN article describes how to create a trigger.
A little "flaw": with this solution you would have to store the new object to the database and read it back afterwards to update your object with the calculated value.
I think the answer provided by lazyberezovsky on another SO question is the straight forward solution to this problem Entity Framework and Default Date