So in the first part of this series we made some DataObjects and used attributing from the System.Data.Linq.Mapping namespace to make our DataObjects LINQ visible. Then in the second part of this series we made LINQ aware of our child DataObjects along with created the actual data store and a custom DataContext. In this part we will be using LINQ to query our data store.
First thing we will insert some data. This can be achieved by instanciating our custom DataContext and passing it a connection string, then using it as we would any other LINQ DataContext.
We can create new instances of all the classes Animal, Penguin, and Monkey then set all the properties and then use our DataContext to persist the changes back to our data store.
Now if we just call all the data from the Animals table via LINQ, by default all the DataObjects returned will look like the Animal class. We can however, select everything from our of the Animals table in our LINQ DataContext and then distinguish what it is then type cast it to gain access to the other properties in the DataObject type. To do this we would do something like this:
Now when we get everything from the database in the query above, it all looks like an Animal. With simple if statements testing the type of each "a" on the iteration, we can then type cast it to gain access to the extended properties of the Penguin and Monkey DataObjects.
Now one more thing you might like to do, is pull out data based on what type it is. Let's take for instance creating a query that pulls out only the Penguins in our database. To achieve something like this we could do like so:
There you have it! If you follow the steps outlined in these three articles, you should be up and running with custom entity classes and inheritance before you know it. Just remember, if you need more insight you can find more information check out the LINQ to SQL MSDN Article here.
Here is the code I used for the articles:
LinqInheritance01.zip (168.47 kb)