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;
        }
    }

9 comments:

Anonymous said...

You were very HelpFull!

We are eternaly grateful!

Anonymous said...

Respect, guy!

davitz38 said...

i guess this a good solution. the other solution would be to put the default value getutctime() in sqlserver, but i think only EF4 allows you to skip a field with StoreGeneratedPattern: computed

Anonymous said...

Sory, EF4 does not solve this problem. StoreGeneratedPattern: computed (or identity) always sends NULL to database, so DB default values are never used.
Microsoft treats this topic as a feature request, not as a bug.
https://connect.microsoft.com/VisualStudio/feedback/details/432777/ado-net-entity-framework-nullable-types

Anonymous said...

I'm probably being dense, but where do you put this code?

Thanks in advance!

Adivera said...

In a partial class in the same namespace of your entitycontainer and with the same name as the entity which you would like to modify...

Cheers
Roberto

Peter Gfader said...

@Anonymous
Roberto said it better than I could...

Thanks!

Cori said...

Looks like my response didn't make it through; I posted the previous anonymous question.

What Roberto said is pretty much what i figured, and indeed method calls in the constrictor of the partial class get called when the list view renders, once for each row. However, what I was really looking for was how to default the field values on the insert view, and the constrictor doesn't get called then ( which makes sense from a certain standpoint).

I ended up handling this by modifying the field templates to default the field values when the field is being rendered for specific columns. Did I misinterpret the problem this solution was intended to solve, or did I get something else wrong? Am I likely to encounter problems with my solution?

Asava Samuel said...

Peter

This is even better than Entity Framework:
https://www.kellermansoftware.com/p-47-net-data-access-layer.aspx

Post a Comment

Latest Posts

Popular Posts