views:

2032

answers:

6

I have a Date column in table which has default value or binding as getutcdate(). I want to use this in entity framework.On generating EDM I was able to find "Default Value " property at column level but I think it is for hardcoded value.

Please let me know how can I use default value specified in database.

Thanks, Mak

A: 

Don't know, but I'll remember this post if I find out ...

Ok, found it .. and it seems to work on my stuff. Your mileage may vary:

http://cs.rthand.com/blogs/blog_with_righthand/archive/2007/05/02/Inserting_2F00_Updating_2F00_Deleting-records-containing-timestamp-columns-in-ADO.NET-Entity-Framework.aspx

brad
+2  A: 

StoreGeneratedPattern = "Computed" is not the same as a default value, because this property would be updated EVERY TIME with the default value in the database.. meaning it is impossible to update it manually.

+1  A: 

You can set the StoreGeneratedPattern to Identity, in which case EF reads the value returned from the database after executing the INSERT statement. The problem with this approach is that the next time the XML mapping is generated, your change will be lost.

Another way to do it is to set the value yourself in your code to DateTime.UtcNow. You could set this in your entity's constructor (define a new constructor if necessary), or you could set it in your own event handler for your context's SavingChanges event (see How to: Execute Business Logic When Saving Changes (Entity Framework) for an example of handling the SavingChanges event).

mvr
A: 

Here is a good post describing how to solve your problem.

Tri Q
A: 

Here's a possible, but not pretty workaround -

Setting Computed on a column will make it read only, but will make the default value work. It's possible to have a real Computed column, say "LastChangedAt_computed" that either shows the value of "LastChangedAt_default" or "LastChangedAt_manual".

Now, the computed column shows the value of the default column, unless the manual column is not-null, in which case it is shown. In the model, the StoragePattern of the default column needs to be "Computed".

It's an ugly solution, but it should work.

Thanks,
Asaf

Asaf R
A: 

Implementing the OnCreated event for the entity is the solution I have found. I had a Guid property that I wanted to be populated. By default it was being populated with all zeros (00000-0000-00000-etc). By adding the following to my partial class of the entity I was able to deal with the issue.

partial void OnCreated()
{
    Guid = Guid.NewGuid();
}
Jon