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
How to set default values for DateTime and Enums
-
- Posts: 21
- Joined: Tue 07 Jan 2014 12:38
-
- Posts: 21
- Joined: Tue 07 Jan 2014 12:38
Re: How to set default values for DateTime and Enums
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
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;
- 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; } }
Re: How to set default values for DateTime and Enums
Thank you for sharing your solution.