My fantastic Webdings Logo

Reamped.NET

XML Thingey... It's a Technical Term


Custom Entity Classes Using LINQ to SQL Part 3 - Queries

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)

 

kick it on DotNetKicks.com


Comments

Ron Larvick

Very, very cool series!  This really opened my eyes to what goes on under the covers.  If you do any more in the series, I would like to see how you can do master-details of the newly created custom objects in a grid with CRUD functionality Smile



Ira

Thanks for the compliments. The master-details scenario is a great idea. I will try to put something together on that and get it up here for you in the near future.



Oscar Fraxedas

Nice work. Thanks for sharing.



Comments are closed