How to set default values for DateTime and Enums

Discussion of open issues, suggestions and bugs regarding Entity Developer - ORM modeling and code generation tool
Post Reply
strandedpirate
Posts: 21
Joined: Tue 07 Jan 2014 12:38

How to set default values for DateTime and Enums

Post by strandedpirate » Tue 07 Jan 2014 22:29

I need to set the default for a field of type DateTime to DateTime.UtcNow and I also want to set the default value for fields of a custom Enum type.

How do I do this?

The Enum fields are disabled in the editor and DateTime fields expect a string.

Examples:
CreatedOn = DateTime.UtcNow; // datetime
AvatarTypeId = AvatarType.Gravatar; // enum

strandedpirate
Posts: 21
Joined: Tue 07 Jan 2014 12:38

Re: How to set default values for DateTime and Enums

Post by strandedpirate » Wed 08 Jan 2014 23:02

Please, not all at once ;(

Thought I'd share my modified DBContext template that allows defaults for DateTime & Enums types. It also fixes a bug with many-to-many fluent api mapping.

https://gist.github.com/Strandedpirate/8326219
  • DateTime fields that are required by your model will be automatically set to DateTime.UtcNow. e.g. CreatedOn = DateTime.UtcNow;
  • To set a value for an Enum there is a new extended property called "Enum Default Value" for every property on in your entities that that you can set to a string in the properties window. e.g. AvatarType = AvatarType.Gravatar;
    Image
  • I also added a partial method called Initialize() to every POCO that you can implement in your own separate partial class and add other initialization for any specific entity to instead of modifying the template.

    Example:

    Code: Select all

    public partial class Post
    {
    	partial void Initialize()
    	{
    		// special entity initialization code goes here
    		LastVisitedOn = DateTime.UtcNow;
    	}
    }

Shalex
Site Admin
Posts: 8247
Joined: Thu 14 Aug 2008 12:44

Re: How to set default values for DateTime and Enums

Post by Shalex » Fri 10 Jan 2014 09:19

Thank you for sharing your solution.

Post Reply