1. Install EF(Entity Framework)
VS > Tools > Library Package Manager > Manage NuGet Packages for Solution > Entity Framework
2. Models > add a class as "EmployeeDBContext.cs"
using System.Data.Entity;
public class EmployeeDBContext: DbContext
{
public DbSet<Employee> Employees { get; set; } //before needing to make a class in model as "employee.cs"
}
3. Add a connection string at "Web.config" for database
<connectionStrings>
<add name="employeeDBContext"
connectionString="server=.; database=halloween; integrated security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>
4. Modify the employee class as a Table attribute
using System.ComponentModel.DataAnnotations.Schema;
[Table("tblEmployee")] // tblEmployee is table name (add a namespace (ctl + .))
5. Controller > add a controller as "EmployeeController.cs"
using MVCSimpleDB.Models;
public ActionResult Details(int id)
{
EmployeeDBContext employeeDB = new EmployeeDBContext();
Employee employee = employeeDB.Employees.Single(x => x.employeeId == id);
return View(employee);
}
6. Add code at "Global.asax" in Application_Start()
using System.Data.Entity;
Database.SetInitializer<MVCSimpleDB.Models.EmployeeDBContext>(null);
7. Run http://localhost/employee/details/2 or 1 or 3 ...