Subscribe Us

LightBlog

Monday, 27 July 2020

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.

No comments:

Post a Comment