In this example we are discussing about Code first approach in entity framework , he will see that how we can create database table into database using code first approach.
Step 1. Create New Empty MVC Project
Step 2. Install Entity framework using package manager console or nuget package manager
Step 3: Add new Model class Emploee.css
Step 5 .Employee.CS
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace EF1.Models{ [Table("Employee")] public class Employee { [Key] public int EmpId { get; set; } [Column(TypeName = "varchar")] [StringLength(50)] public string EmployeeName { get; set; } public string Address { get; set; } public string mobileno { get; set; } }
Step 6: Create connection string into web.config file
Step 7. Create new DataContext class in Models Folder.
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace EF1.Models { public class DataContext : DbContext { public DataContext():base("conn"){} public DbSet Employees { get; set; } } }
Step 8: Update Global.asax
using EF1.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace EF1 { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); Database.SetInitializer(new CreateDatabaseIfNotExists()); } } }
Step 10: Create Home Controller and Index.cshtml view.
using EF1.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace EF1.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { DataContext db=new DataContext (); var data = db.Employees.ToList(); return View(data); } }
Step11 . Run Project
Ouput : Two Database tables will be created Employee and Migration_Histore