CSharpFeeds - All your C# feeds in one place.

Sponsors

Saturday, July 11, 2009

A simple select with LINQ to SQL and without the designer

by sweisfeld via Shawn Weisfeld [MVP] on 7/11/2009 9:57:42 PM

Many folks poo-poo LINQ to SQL because they don’t like designers. On the other hand some developers, myself included, like knowing how things work behind the scenes, for those edge case moments when the designer cannot do something. The most common business case for this is if you want to LINQ to SQL-afy an existing suite of objects. Well using the designers is NOT a requirement of LINQ to SQL.

Lets say for example you had an existing customer table and customer business object:

image image

Lets see if we can get LINQ to SQL to populate a list of customers from the database.

Ok first we need to make sure we have a valid connection string.

image

The next step is to create our DataContext. If you have used LINQ to SQL you will know that this guy does all the heavy lifting when it comes to getting data from and pushing data to the database.

Creating the DataContext is simple. Just create a new class and set its parent class to DataContext. (You will probably need to add a reference to System.Data.Linq.)  Once you have the class created create a private static member called for the mapping source, and a constructor. The mapping source tells LINQ if it should look for attributes on the object, or in an xml configuration file for instructions on how to map the object model to the db model. This constructor will be chained to our base class passing up the mapping source and the connection string.

image

Since we selected an Attribute Mapping Source, lets go and decorate our customer class. using the attributes in the System.Data.Linq.Mapping namespace I tell LINQ to SQL what db table our object maps to and what columns each of the properties map to.

image

The next step is to add a helper method to our Data Context exposing the data so we can easily query it.

image

Now we can just write our LINQ query, just like normal.

image

That is it a simple LINQ to SQL query without the designer. Here are the results of the above query.

image

In my next post I will kick this up a notch by using a stored procedure to get these same results.

email it!bookmark it!digg it!

Original Post: A simple select with LINQ to SQL and without the designer

Subscribe

New Feed

Product Spotlight

Recently Updated Sources

Legal Note

The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.

Advertise with us