Have you ever wanted to use the LINQ technology without being bound to the "LINQ to SQL Classes" item in Visual Studio? I know I have! I was wondering if there was a way to use LINQ, but doing it with my own DataObjects in either a ground up project or an add in scenario. It just so happens you can. You can define your own DataObjects and then map them to a database table using attributes. Take note that all of your DataObject or "Entity Class" attributes are found in the System.Data.Linq.Mapping namespace. So let's get started.
I am going to build a heirarchy of animals, so my first DataObject will be an Animal object Here is how I will define my Animal object.
Now that we have our Animal object, we can then attribute it to give it visibility to LINQ
The entire Animal.cs code file:
using System.Configuration;
using System.Linq;
using System.Data.Linq.Mapping;
namespace Rollem.LinqInheritance
{
///
/// Summary description for Animal
///
[Table(Name = "dbo.Animals")]
public class Animal
{
private int _animalID;
private string _name;
private DateTime _dateOfBirth;
[Column(IsPrimaryKey = true, IsDbGenerated = true)]
public int AnimalID
{
get { return _animalID; }
set { _animalID = value; }
}
[Column]
public string Name
{
get { return _name; }
set { _name = value; }
}
[Column]
public DateTime DateOfBirth
{
get { return _dateOfBirth; }
set { _dateOfBirth = value; }
}
}
}
Now if you wanted to, you could make a table called "Animals" in your database and as long as your column names are the same as your public property names this DataObject can be used by LINQ. The "Table" attribute just specifies what table in your database that the DataObject represents, and then each property that will be held in the table just needs the "Column" attribute. On the AnimalID in our table, I am going to set that as the primary key and I am also going to give it an identity seed. It is important to mark these special cases as we have done above on the AnimalID column.
For some extra fun, we will add a couple of child objects to our Animal DataObject. We can set them up like so:

Then go ahead through and put the "Column" attribute on all of the properties in our child classes. You will not have to use the "Table" attribute on the child classes, as LINQ has a table per class heirarchy approach to DataObjects.
If you have no inheritance in your data model the you should be set by just making your DataObjects and setting your "Table" and "Column" attributes. Then all you have left to do is make your own DataContext and you are off to the races.
For a little more insight, check out the LINQ to SQL MSDN Article here.
Next time, we will set up LINQ inheritance mapping on our parent class, create our data context and more!