ASP.NET MVC > Models

Create a model based on database table in ASP.NET MVC

How to create a model based on 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.

Ideally the name of the Model should be singular and the name of the database table should be plural for example PersonalDetail is the name of the model class and corresponding table name would be PersonalDetails in the database.

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 above to the properties of this Model. Attributes are wrapped with "[" and "]" above the property name.

The best way to add the namespace used for the objects 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.

For example, we have used [Key] attribute and its namespace doesn't exists in the class, so we have pressed "Ctrl + ." keeping the cursor on the [Key] attrubite and we got intellisense and then clicked the first namespace. This will add "using System.ComponentModel.DataAnnotations" namespace at the top of the class.

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: 34858 | Post Order: 32



Write for us






Hosting Recommendations