Professional Documents
Culture Documents
4. DataAnnotations
Steps:
This walkthrough illustrates how to work with the Code First Approach of Entity
Framework.
Steps
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace DayII_Models.Models
{
public class Items
{
[Key]
public int ItemCode { get; set; }
public String ItemName { get; set; }
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace DayII_Models.Models
{
public class ItemsContext : DbContext
{
public DbSet<Items> Items { get; set; }
}
}
4. Open Web.config file and add the connection string <connectionStrings> tag.
<connectionStrings>
<add name="ItemsContext"
connectionString="Your connection string goes here"
providerName="System.Data.SqlClient" />
</connectionStrings>
}
}
}
PM>add-migration Initial
Namespace DayII_Models.Migrations
{
using System;
using System.Data.Entity.Migrations;
PM> update-database
namespace DayII_Models.Models
{
public class Items
{
[Key]
public int ItemCode { get; set; }
public String ItemName { get; set; }
}
}
2. Open Configuraion.cs
namespace DayII_Models.Migrations
{
using System;
using System.Data.Entity.Migrations;
Build the solution, and then enter the " update-database" command in the Package
Manager Console window.
PM>update-database
Refresh the database and check if structure of the table has been modified and the
data has been updated in the table as shown below
Adding validations
using System.ComponentModel.DataAnnotations;
public class SalesItems
{
[Key]
public int ItemCode { get; set; }
[Required(ErrorMessage="Item name cannot be Null")]
[StringLength(50)]
public String ItemName { get; set; }
[Required]
public int Price { get; set; }
//new field
[Range(25,1000)]
public int Discount { get; set; }
}
namespace DayII_Models.Migrations
{
using System;
using System.Data.Entity.Migrations;
PM>update-database
Model Validation-II
Day -II Perform validations
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
// .+\\@.+\\..+"
namespace FirstApplication.Models
{
public class GuestResponse
{
[Required(ErrorMessage="Please enter Name;It cannot be null")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter Phone;It cannot be null")]
[RegularExpression("[0-9]{10}", ErrorMessage="enter 10 digit number")]
public string Phone { get; set; }
[Required(ErrorMessage = "Please specify whether you'll attend")]
public bool? WillAttend { get; set; }
}
}
EventForm.cshtml
@model FirstApplication.Models.GuestResponse
@{
ViewBag.Title = "EventForm";
}
<h2>EventForm</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary()