Ad Unit (Iklan) BIG

crud operations using mvc scaffolding with linq to sql

crud operations using mvc scaffolding with linq to sql
in this article, i will show you crud operations using mvc scaffolding with linq to sql.

---table script---
create table Employee
(
   id int primary key identity(1,1),
   name varchar(50),
   salary decimal(18,2)
)

here must add package in project solution :

   System.Data.Linq

---model class---
[Table]
public class Employee
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true)]
    public int id { get; set; }
    [Column]
    public string name { get; set; }
    [Column]
    public decimal salary { get; set; }
}

---employee controller--
DataContext dc = new DataContext("Data Source=.;Initial Catalog=TESTDB;Integrated Security=True");

public ActionResult Index()
{
    IEnumerable<Employee> emp_data = dc.GetTable<Employee>();
    return View(emp_data);
}

public ActionResult Create()
{
    return View();
}

[HttpPost]
public ActionResult Create(Employee emp)
{
    dc.GetTable<Employee>().InsertOnSubmit(emp);
    dc.SubmitChanges();
    return RedirectToAction("Index");
}

[HttpGet]
public ActionResult Edit(int id)
{
    Employee emp = dc.GetTable<Employee>().Single(x => x.id == id);
    return View(emp);
}

[HttpPost]
public ActionResult Edit(Employee empobj)
{
    Employee emp = dc.GetTable<Employee>().Single(x => x.id == empobj.id);
    UpdateModel(emp);
    dc.SubmitChanges();
    return RedirectToAction("Index");
}

[HttpGet]
public ActionResult Delete(int id)
{
    Employee emp = dc.GetTable<Employee>().Single(x => x.id == id);
    return View(emp);
}

[HttpPost]
public ActionResult Delete(Employee empobj)
{
    Employee emp = dc.GetTable<Employee>().Single(x => x.id == empobj.id);
    dc.GetTable<Employee>().DeleteOnSubmit(emp);
    dc.SubmitChanges();
    return RedirectToAction("Index");
}

note: accoding to action method you can add scaffolding templet on view.

Post a Comment

0 Comments