So, I am going to talk about LINQ. There are a lot of great resources out there on LINQ. I am going to have a series of articles on building an application utilizing LINQ, WCF and other technologies. Some of the things that I want to show is how you can use LINQ as part of your testing. So lets get started.
So the first thing that we need is some data to define. The sample application that we are going to build is a simple home inventory system. The image to the right defines a Customer.
There is three ways that we can generate this data definition.
The second option is the simplest but you don't have very much control of what gets generated. So, I favor creating my files manually, because I have total control and I only define what I need (Option 3).
Make sure that you have a reference to System.Data.Linq.
public class Customer
[Column(Name="Id", IsDbGenerated=true, DbType="int", IsPrimaryKey=true)]
public int Id
public string FirstName
In this step we are going to create a data context to handle our database interactions. First, we need to create a class that derives from System.Data.Linq.DataContext. Second, we create a static Create method to handle the initialization of the class for ease of use. Third, define tables, procedures and queries. Below show a simple class for our use.
public class InventoryDBDataContext : DataContext
public InventoryDBDataContext(string connection)
public static InventoryDBDataContext Create()
string connection = ConfigurationManager.ConnectionStrings["InventoryDB"].ConnectionString;
return new InventoryDBDataContext(connection);
public Table<Customer> Customers;
You will notice that the static Create method allows for the hiding of implementation. In the next part you will see how this is helpful.
Well, we finally are ready to get data. To get a list of customer, all that we have to do is the following:
using (InventoryDBDataContext context = InventoryDBDataContext.Create())
var customers = (from c in context.Customers
Assert.IsTrue(customers.Count > 0);
Now you see that we are now containing the calls with a "using" statement. This allows for better garbage collection. With the 3.0 framework, you can allow a runtime definition of variables by just using the "var" keyword. The selection of the data looks very familiar with TSQL statements. The selection pieces defined:
We have now completed the basics with getting started with LINQ. Next time we will take a deeper look into LINQ queries and other customization of our classes.
Let me know what you think. Next time we will cover how to use XML LINQ in unit testing our code.