ASP.NET MVC > Models

Auto increment property in Model in ASP.NET MVC

How to create an auto increment property in the Model?


To create auto increment property in Model, we use DatabaseGenerated attribute to the property. To demonstrate this, we are going to see how to create a Model that contains auto increment property corresponding to the auto increment field of the database  table.

Right click Models folder from the Solution Explorer and select Add > Class

Write the name of the Model you want to create, in this case PersonalDetail and click Add. 

A class file named PersonDetail.cs is added into Models folder. Now, let’s assume that we want to create a Model corresponding to the following table in the database. Notice that database table name is also PersonalDetail and AutoId field is the auto increment field. 

To do that we need to create properties corresponding to the fields of the database table and our Model looks like below.

/Models/PersonalDetail.cs

using System; 
using System.Collections.
Generic; using System.Linq; 
using System.Web; 
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema;  
namespace WebApplication1.Models { public class PersonalDetail { [Key] [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOpt ion.Identity)] public int AutoId { get; set; }
[StringLength(20, MinimumLength = 4, ErrorMessage = "Must be at least 4 characters long.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please write your LastName")] public string LastName { get; set; } public int Age { get; set; } [Display(Name = "Is Active?")]
public bool Active { get; set; } } }

Remember that we need to add last two namespaces in order to add attributes to the properties. Let’s talk about attributes added to the properties of this Model. 

The best way to add the namespace is press [Ctrl + .] by keeping the cursor on the attributes. It will give a IntelliSense as the probable namespace and then select the appropriate one.

Description of the attributes added to this Model. 

  • [Key] – Used to mark the property as Primary key
  • [DatabaseGenerated] – used to mark the field as database generated (auto increment field in the database) 
  • [StringLength] - used to limit the length of the characters allowed in this field 
  • [Required] – used to mark the property as mandatory 
  • [Display] – used to bring a description Label for the property when view is scaffold.
 Views: 7603 | Post Order: 34



Write for us