Entity Framework: How to set Defaultvalues for DateTime fields

It's easy I thought, just select the Property of the EntityType and set the Default Value in the Properties window to: DateTime.Now
image

But it's not

Defaultvalues get validated on Compile time not on Design time.
So after Rebuild you get:

Error      1              
Error 54: 
Default value (System.DateTime.Now) is not valid for DateTime. The value must be in the form 'yyyy-MM-dd HH:mm:ss.fffZ'.                
C:\DataPeterGfader\ProjectsTFS\ImportantClient\Business\Entities\MyImportantModel.edmx 

How to set then the default value?

Use the constructor of the Entity.
Yes I know that it's not nice to to this manually!

Example code

    public partial class Transactions
    {
        public Transactions()
        {
            //HACK: To prevent this error: {"SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM."}
            this.LastModified = System.DateTime.Now;
        }
    }

Latest Posts

Popular Posts