Default value in mvc model using data annotation

C#.Netasp.net Mvc

C# Problem Overview


Is it possible using data annotations to add default value for int property

something like

[DefaultValue=1]
public int MyId {get; set;}

C# Solutions


Solution 1 - C#

Try this - set the default value in the constructor:

public class YOURMODEL
{
    public int MyId { get; set; }  

    public YOURMODEL()
    { 
        MyId = 1;       
    }
}

Later addition by other user: Since C# 6.0 (2015) this simpler syntax has been allowed:

public class YOURMODEL
{
    public int MyId { get; set; } = 1;
}

Solution 2 - C#

Use [DefaultValue(false)].

(Reference)

Solution 3 - C#

The constructor method is correct of course (as per @Nilesh) but this solution doesn't address any legacy data you might have already created in your database.

You can also update your legacy data by generating the migration and then adjusting the AddColumn method thusly...

AddColumn("dbo.Orgs", "MyId", c => c.Int(nullable: false));

changes to:

AddColumn("dbo.Orgs", "MyId", c => c.Int(nullable: false, defaultValue: 1));

Note, this will also create a database trigger that would automatically update the default value on INSERT so you don't technically need the constructor method from the database perspective but setting the value using the constructor is still the best practice.

Solution 4 - C#

You can only do this using the class' constructor. Your code should thus look like this:

public class MyModel
{
    public MyModel()
    {
        MyId = 1;
    }

    public int MyId {get; set;}
}

This will lead to the MyId property being set to 1 whenever a new instance of the class is made. However, if model binding detects that the user has specified a value for MyId, it will overwrite the default value with the user-specified one.

Solution 5 - C#

using System.ComponentModel;

namespace EMS.Models
{
    public class Admission
    {
        [DefaultValue(false)]
        public Boolean LCStatus { get; set; }

        [DefaultValue("India")]
        public string Country{ get; set; }
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1765862View Question on Stackoverflow
Solution 1 - C#Nilesh GajareView Answer on Stackoverflow
Solution 2 - C#bellonaView Answer on Stackoverflow
Solution 3 - C#spadelivesView Answer on Stackoverflow
Solution 4 - C#Erik SchierboomView Answer on Stackoverflow
Solution 5 - C#Pankaj LahotiView Answer on Stackoverflow