is there "elegant" way to give specific property a default value ?
Maybe by DataAnnotations, something like :
[DefaultValue("true")]
public bool Active { get; set; }
Thank you.
is there "elegant" way to give specific property a default value ?
Maybe by DataAnnotations, something like :
[DefaultValue("true")]
public bool Active { get; set; }
Thank you.
Set the default value for the column in table in MSSQL Server, and in class code add attribute, like this:
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
for the same property.
What I did, I initialized values in the constructor of the entity
Note: DefaultValue attributes won't set the values of your properties automatically, you have to do it yourself
The above answers really helped, but only delivered part of the solution. The major issue is that as soon as you remove the Default value attribute, the constraint on the column in database won't be removed. So previous default value will still stay in the database.
Here is a full solution to the problem, including removal of SQL constraints on attribute removal. I am also re-using .NET Framework's native
DefaultValue
attribute.Usage
For this to work you need to update IdentityModels.cs and Configuration.cs files
IdentityModels.cs file
Add/update this method in your
ApplicationDbContext
classConfiguration.cs file
Update your
Configuration
class constructor by registering custom Sql generator, like this:Next, add custom Sql generator class (you can add it to the Configuration.cs file or a separate file)
Just Overload the default constructor of Model class and pass any relevant parameter which you may or may not use. By this you can easily supply default values for attributes. Below is an example.
I found that just using Auto-Property Initializer on entity property is enough to get the job done.
For example:
It's simple! Just annotate with required.
the resultant migration will be:
If you want true, change the defaultValue to true in the migration before updating the database