21 March 2013

CRUD using LINQ To Entities (The Least Thing That You Should Know)

Early this year, I began to really love LINQ over SQL in developing some small to medium-sized projects.

Since this is the first time that my team will implement LINQ, I just want to share some of the "least things" that they should know to implement CRUD using LINQ To Entities.

In my example, I use a Database-First approach where Employee is the table name, EmployeeId is the primary key, and MyEntity() is the entity name created by the designer.


SELECT

public IQueryable<Employee> GetAllEmployees()
    {
        var ctx = new MyEntity();
        return ctx.Employees.Select(y => y);    
    }



INSERT

public int InsertEmployee(Employee z)
    {
        var ctx = new MyEntity();
        Employee x = new Employee();
        x.LastName = z.LastName;
        x.FirstName = z.FirstName;
        x.Telephone = z.Telephone;
        x.Salary = z.Salary;
        x.DateHired = z.DateHired;
        x.DateCreated = z.DateCreated;
        x.UserId = z.UserId
        ctx.AddToEmployees(z);
        ctx.SaveChanges();
        return z.EmployeeId;              
     }


UPDATE

public void UpdateEmployees(Employee z)
    {
        var ctx = new MyEntity();
        var x = ctx.Employees.Where(y => y.EmployeeId == z.EmployeeId).FirstOrDefault();
        x.LastName = z.LastName;
        x.FirstName = z.FirstName;
        x.Telephone = z.Telephone;
        x.Salary = z.Salary;
        x.DateHired = z.DateHired;
        x.DateCreated = z.DateCreated;
        x.UserId = z.UserId;
        ctx.SaveChanges();
     }



DELETE

public void DeleteEmployee(Employee z)
    {
      var ctx = new MyEntity();
      var x = ctx.Employees.OrderByDescending(y => y.EmployeeId).FirstOrDefault();
      ctx.Employees.DeleteObject(x);
      ctx.SaveChanges();
    }



Note: This is just a very simple CRUD implementation for learning purposes only. In production, make sure to include exceptions and some rules.

No comments:

Post a Comment