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.
Creating model corresponding to database table
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.
In ideal scenario, the database table name should be plurised (like instead of PersonalDetail, it should be PersonalDetails).
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.
What do you think?
I hope you will enjoy to create Model while programming with Asp.Net MVC. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.
No comments:
Post a Comment