Wednesday, November 21, 2007

Simple Data Access in Visual Studio 2008 Using LINQ to SQL

Often when I have to throw together a quick sample, it will involve some sort of data from the database.  Prior to C# 3.0, the quickest thing I could do was create the sample data structures, put together some SQL, and then use the Microsoft Data Access Application Block to do the data access from C#.

Now, I can do this much faster.  The first thing I'll do is create the table(s) in SQL Server.  Then I'll go to my Visual Studio 2008 project and add new LINQ to SQL Classes:

Add DBML File

After that, I'll open the Server Explorer window, and expand my connection, and my tables, and drag my tables onto the .dbml file's designer surface

DBML Surface

And now, I can just start writing LINQ against the new Data class.  Below is an example of some LINQ that gets a collection of contacts out of the database.

ContactDataDataContext dataContext = new ContactDataDataContext();
var items = (from p in dataContext.GetTable<Contact>() select p);
Contact[] contacts = items.ToArray<Contact>();

Pretty great stuff.  I'm up and running with a SQL backend in a jiff.