Geeks With Blogs
Han Cheng C#, ASP.NET, Microsoft Technologies

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();
Posted on Saturday, October 31, 2009 9:51 PM LINQ | Back to top


Comments on this post: CRUD operations using LINQ

# re: CRUD operations using LINQ
Requesting Gravatar...
For your create example, you forgot the "saving to the database" part:

Departments.InsertOnSubmit(newDept);
SubmitChanges();


Also, should line 2 of "Delete Record" be
Departments.DeleteOnSubmit( dept );

(with the "s" on "Departments")
Left by James Curran on Nov 06, 2009 11:56 PM

# re: CRUD operations using LINQ
Requesting Gravatar...
Thanks for pointing that out!

I have corrected the errors.
Left by Han Cheng on Nov 07, 2009 10:38 AM

Your comment:
 (will show your gravatar)


Copyright © Han Cheng | Powered by: GeeksWithBlogs.net