Relation mapping

by Alexey Shirshov April 15, 2009 09:59

In the last post I wrote that I'm finish with AdventureWorks mapping. I was wrong. :) There are still a lot of things I'm gonna show you.

Ok, let's talk about relations. In the Store class there is a property SalesPerson which means one to many relation between Store and SalesPerson. One SalesPerson has multiple Stores and one Store has single SalesPerson.

So in our model there isn't property in SalesPerson class that returns collection on Stores. Let's add it.

        public QueryCmd Stores
        {
            get
            {
                return Store.Query
                    .Where(Ctor.prop(typeof(Store), "SalesPerson").eq(this));
            }
        }

As you can see we add Stores property which returns QueryCmd. We have seen QueryCmd in previous examples. It's not a collection, it is query command which can be used to get collection by executing it. In the following example we invoke ToList method to execute command and get collection of Store class instances.

            foreach (exam1sharp.Sales.Store s in p.Stores.ToList())
            {
                Console.WriteLine("Store id: {0}, name: {1}, sales territory: {2}",
                    s.ID,
                    s.Name,
                    s.SalesPerson.SalesTerritory.Name);
            }

where p is SalesPerson variable. It can be obtained in the following manner

            exam1sharp.Sales.SalesPerson p = exam1sharp.Sales.SalesPerson.Query
                .Where(Ctor.prop(typeof(exam1sharp.Sales.SalesPerson),"ID").eq(280))
                .Single() as exam1sharp.Sales.SalesPerson;

Here we select SalesPerson with ID property equals to 280.

Tags:

Quickstart

Add comment


(Will show your Gravatar icon)  

Enter the word
captcha word
(hear it spoken)


  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen | Modified by Mooglegiant

The Author

My name is Alexey Shirshov. I'm a professional developer with wide specialization. I prefer VB.NET to C#, I hate ASP.NET but there is no better than it. You can contact me by this page.