Attention: We are retiring the ASP.NET Community Blogs. Learn more >

First Crack at LINQ and Visual Studio 2008 (Codename Orcas)

I started working with VS2008 pretty regularly about a month ago.  One of the first things I wanted to try out was LINQ.  I had been to assorted sessions at PDC, TechEd, MIX, and some other shows where they covered LINQ, and I was pretty impressed.  In the past, figuring out how to use a new VS feature was almost like a treasure hunt.  You could pick up clues here and there, but putting it all together was challenging.  I'm not sure if it's due to Scott Gu's blogs, or the intuitive nature of LINQ (or both), but I was pleasantly surprised that I could do it! 

Using the LINQ to SQL classes, I created a DataModel which mapped to my SQL tables.  It was then just a bit of simple LINQ to bind the records to my table.  Basically in 20 minutes I had created a LINQ based data structure and hooked up my tables to create a master details view.  Now that's not to say that I've mastered LINQ, but that does speak to it's intuitive nature. 

My back end data was the Adventure Works database served up from SQL.  Here's a look at my DataBinding code:

DataClassesDataContext context = new DataClassesDataContext();
var employees = from emp in context.Employees
                select new
                {
                    EmployeeID = emp.EmployeeID,
                    Name = emp.Contact.LastName + ", " + emp.Contact.FirstName,
                    BirthDate = emp.BirthDate
                };
this.GridView1.DataSource = employees;
this.GridView1.DataKeyNames = new string[]{"EmployeeID"};
this.GridView1.DataBind();

And then my detailsview code:

DataClassesDataContext context = new DataClassesDataContext();
var contact = from c in context.Employees
               where c.EmployeeID == (int)this.GridView1.SelectedDataKey.Value
               select c.Contact;
this.DetailsView1.DataSource = contact;
this.DetailsView1.DataBind();

Something worth pointing out - in the first snippet, notice that I'm doing a "select new"  I'm using an anonymous type here so that I don't have to stub out a class just to represent my data.  This feature is great.  I always thought there must be a better way than stubbing out dummy classes just to act as my business objects.  Now that's not to say that there's no need for creating separate business object classes anymore, but this makes a nice alternative for the simpler cases, where a full business object layer may be overkill.   

3 Comments

Comments have been disabled for this content.