Default value in mvc model using data annotation

前端 未结 5 1518
小鲜肉
小鲜肉 2020-12-29 18:01

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

something like

[DefaultValue=1]
public int MyId {get; set;}
5条回答
  •  青春惊慌失措
    2020-12-29 18:49

    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.

提交回复
热议问题