Han Cheng

C#, ASP.NET, Microsoft Technologies

  Home  |   Contact  |   Syndication    |   Login
  3 Posts | 0 Stories | 2 Comments | 0 Trackbacks

News

Archives

Post Categories

Saturday, October 31, 2009 #

I will use the AdventureWorks database to demonstrate how to perform CRUD operations using LINQ. You can use LINQPad (a free tool) to execute your C# statements without going through the hassle of writing a program using Visual Studio 2008.

Launch LINQPad, add your SQL Server Connection and select AdventureWorks as the Database. Remember to select C# Statement(s) as the Language Type.

Create Record

1:  Department newDept = new Department()
2: {
3: Name = "Consulting",
4: GroupName = "Consulting",
5: ModifiedDate = DateTime.Now
6: };
7:
Departments.InsertOnSubmit(newDept);
8:
SubmitChanges();

Retrieve Record

1:  var department = from dept in Departments
2: where dept.Name == "Consulting"
3: select dept;
4: department.Dump();

Update Record

1:  Department dept = (from dept in Departments where dept.Name == "Consulting" select dept).Single();
2: dept.GroupName = "Consulting Services";
3:
dept.ModifiedDate = DateTime.Now;
4:
SubmitChanges();

Delete Record

1:  Department dept = (from dept in Departments where dept.Name == "Consulting" select dept).Single();
2:
Departments.DeleteOnSubmit( dept );
3:
SubmitChanges();