You are on page 1of 9

This document includes the following walkthroughs

1. Database first Approach

2.Code First Approach

3. Adding New Field

4. DataAnnotations

Walkthrough database First approach

Steps:

1. Launch Visual Studio to create new ASP.NET MVC application .


2. Choose File-New->Web->ASP.NET Web Application. From the templates
choose MVC template and click Ok button. Following this, Visual studio
creates the solution for the application with the necessary files and
directory structure.
3. In the Models folder add an Entity Data Model as below
a. Models folder -> add -> Ado.net Entity Data Model
4. Specify the name in the Item name name box and click on Add button. this
Enityt Data model Wizard.
5. From the Wizard choose EF designner from Database and click next
button.
6. Specify the connection string in Choose your Data connection wizard.
7. Choose the table from the choose your database objects & setting wizard
and click finish button.
8. The above steps adds a .edmx file which includes the selected database
table. VS also adds the Entity class & Datacontext class
9. Build the application.
10.With the above step you have completed the creation of Model using EF
Database first approach

Walkthrough -EF Code First Approach

This walkthrough illustrates how to work with the Code First Approach of Entity
Framework.

Steps

1. Create ASP.NET MVC application.


2. Right click Model folder ->Add New Item->class and code it as below.

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; }

public int Price { get; set; }


}
}

3. Add another class to the same folder and code it as below.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

//DbContext class is available in System.Data.Entity namespace.

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>

5. Build the application.


6. Go to Tools->Nuget Package Manager->Package manager Console . In the
console window type the command as below

PM> Enable-Migrations -ContextTypeName ItemsContext


namespace DayII_Models.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using DayII_Models.Models;
internal sealed class Configuration :
DbMigrationsConfiguration<DayII_Models.Models.ItemsContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}

protected override void Seed(DayII_Models.Models.ItemsContext context)


{
// This method will be called after migrating to the latest version.

// You can use the DbSet<T>.AddOrUpdate() helper extension method


// to avoid creating duplicate seed data. E.g.
//
context.Item.AddOrUpdate(
p => p.ItemName,
new Items { ItemName = "Lantops" ,Price=65000},
new Items { ItemName = "USB", Price=5500 },
new Items { ItemName = "HeadPhones", Price=155}
);

}
}
}

Next type the command

PM>add-migration Initial

This creates _<somenumber>_initial.cs

Namespace DayII_Models.Migrations
{
using System;
using System.Data.Entity.Migrations;

public partial class Initial : DbMigration


{
public override void Up()
{
CreateTable(
"dbo.Items",
c => new
{
ItemCode = c.Int(nullable: false, identity: true),
ItemName = c.String(),
Price = c.Int(nullable: false),
})
.PrimaryKey(t => t.ItemCode);

public override void Down()


{
DropTable("dbo.Items");
}
}
}

Next type the command

PM> update-database

Part-II - Adding new column


1. Modify the class to add a new property Discount to the class.

namespace DayII_Models.Models
{
public class Items
{
[Key]
public int ItemCode { get; set; }
public String ItemName { get; set; }

public int Price { get; set; }

public int Discount { get; set; }

}
}

2. Open Configuraion.cs

protected override void Seed(DayII_Models.Models.ItemsContext context)


{
// This method will be called after migrating to the latest version.

// You can use the DbSet<T>.AddOrUpdate() helper extension method


// to avoid creating duplicate seed data. E.g.
//
context.SalesItem.AddOrUpdate(
p => p.ItemName,
new SalesItems { ItemName = "Lantops" ,Price=65000, Discount=50},
new SalesItems { ItemName = "USB",Price=5500 ,Discount=100},
new SalesItems { ItemName = "HeadPhones" , Price=155,Discount=25}
);

PM> add-migration Discount

Adds 201508271754275_Discount.cs file with code as listed below

namespace DayII_Models.Migrations
{
using System;
using System.Data.Entity.Migrations;

public partial class Discount : DbMigration


{
public override void Up()
{
AddColumn("dbo.SalesItems", "Discount", c => c.Int(nullable: false));
}

public override void Down()


{
DropColumn("dbo.SalesItems", "Discount");
}
}
}

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; }
}

type the below command


PM>add-migration validations

namespace DayII_Models.Migrations
{
using System;
using System.Data.Entity.Migrations;

public partial class validations : DbMigration


{
public override void Up()
{
AlterColumn("dbo.Items", "ItemName", c => c.String(nullable: false, maxLength: 7));
}

public override void Down()


{
AlterColumn("dbo.Items", "ItemName", c => c.String());
}
}
}

Type the below command

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()

<p> Your Name : @Html.TextBoxFor(x=>x.Name)</p>

<p> Your Phone : @Html.TextBoxFor(x => x.Phone)</p>


<p>
Would you like to attend ?
@Html.DropDownListFor(x=>x.WillAttend , new[]
{
new SelectListItem()
{Text="Yes", Value=bool.TrueString},
new SelectListItem()
{Text="No", Value=bool.FalseString}
}, "Choose an Option")
</p>
<input type="submit" value="Submit Invite"/>

You might also like