1

Can anyone tell me, how to use the default values from Entity Framework for a datetime column?

3 Answers 3

1

EF designer doesn't have any useful support for configuring default values for a data time. The best way is to initialize default values in constructor of your entity. Each entity is partial class so you can create your own partial part and use:

public partial class YourEntity
{
    public YourEntity()
    {
        YourDateProperty = DateTime.Now;
    }
}

The same is valid for code only mapping but in such case you don't need partial part because you can define constructor directly in your manually created entity class.

Sign up to request clarification or add additional context in comments.

2 Comments

If using EF 4.1 code first, the entity does not need to be partial.
@olivehour: Yes, I mentioned it in the last sentese.
0

Consider specifying default value in database (column property).

Comments

0

If you only need to use the current time as the default datetime value you can use the TimeStamp attribute in the namespace System.ComponentModel.DataAnnotations to have .NET create a non-nullable Timestamp column in the database table that your entity represents.

[Timestamp]
public Byte[] TimeStamp { get; set; }

Code first allows only one Timestamp property per entity.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.