Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » LINQ » One-Many and One-One relationship using LINQ to SQL

One-Many and One-One relationship using LINQ to SQL

In this article we will start with a basic LINQ to SQL example and then see how we can implement one-many and one-one relationship using ‘Entityref’ and ‘EntitySet’. We have also attached a source which demonstrates the same in a practical manner.

Author Rank:
Technologies: .NET 2.0,Visual C# .NET
Total downloads : 79
Total page views :  4552
Rating :
 0/5
This article has been rated :  0 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
LINQtoSQL.zip
 
Become a Sponsor




Introduction
 
In this article we will start with a basic LINQ to SQL example and then see how we can implement one-many and one-one relationship using 'Entityref' and 'EntitySet'. We have also attached a source which demonstrates the same in a practical manner.

Catch my videos for WCF, WPF, WWF, LINQ , Silverlight,Design patterns , UML and lot on
http://www.questpond.com

Previous LINQ,Silverlight,WCF,WPF and WWF articles

Below are some of my old articles which you would like to refer in case you are not acquainted with .NET 3.5 basic concepts.

  1. This article talks about a complete 3 tier implementation using LINQ :-  http://www.c-sharpcorner.com/UploadFile/shivprasadk/SaPe03262009072217AM/SaPe.aspx?ArticleID=f18c3c3b-523b-4c1c-9ad0-e51476115e4a
     

  2.  WCF FAQ series covering simple to advance concepts :- http://www.c-sharpcorner.com/UploadFile/shivprasadk/122345601022009064602AM/1223456.aspx?ArticleID=d88a04d5-633c-44f8-85fa-09941f2064dd 
     

  3. WPF and Silverlight FAQ series covering layout, animation and bindings. :- http://www.c-sharpcorner.com/UploadFile/shivprasadk/21FAQ04242009031713AM/21FAQ.aspx?ArticleID=1d54da18-1050-4832-905b-0b058a1313fb  
     

  4. Windows work flow FAQ series covering state machines and sequential work flow in detail. :- http://www.c-sharpcorner.com/UploadFile/shivprasadk/12334512312008070235AM/123345.aspx?ArticleID=bd393908-36cc-45c0-b899-30aa44fcf64d
     

Simplest LINQ to SQL example
 
So let's first start with a simple LINQ to SQL example and then we will try to understand how we can establish relationship in LINQ entities.

Step 1:- Define Entity classes using LINQ

When we design project using tiered approach like 3-tier or N-tier we need to create business classes and objects. For instance below is a simple class which defines a class which is mapped to a country table as shown below. You can see we how the class properties are mapped in one to one fashion with the table. These types of classes are termed as entity classes.
 

1.JPG

In LINQ we need to first define these entity classes using attribute mappings. You need to import "System.Data.Linq.Mapping;" namespace to get attributes for mapping. Below is the code snippet which shows how the 'Table' attribute maps the class with the database table name 'Customer' and how 'Column' attributes helps mapping properties with table columns.

        [Table(Name = "Customer")]

        public class clsCustomerEntityWithProperties 
        { 
            private int _CustomerId; 
            private string _CustomerCode; 
            private string _CustomerName; 
            [Column(DbType = "nvarchar(50)")] 
            public string CustomerCode 
            { 
                set 
                { 
                    _CustomerCode = value
                } 
                get 
                { 
                    return _CustomerCode; 
                } 
            } 
            [Column(DbType = "nvarchar(50)")] 
            public string CustomerName 
            { 
                set 
                { 
                    _CustomerName = value
                } 
                get 
                { 
                    return _CustomerName; 
                } 
            } 
            [Column(DbType = "int", IsPrimaryKey = true)] 
            public int CustomerId 
            {
                set
                {
                    _CustomerId = value;
                }
                get
                {
                    return _CustomerId;
                }
            }
        }
    }


Below is a more sophisticated pictorial view of the entity classes mapping with the customer table structure.

2.JPG

Step 2:- Use the datacontext to bind the table data with the entity objects.

The second step is use the data context object of LINQ to fill your entity objects. Datacontext acts like a mediator between database objects and your LINQ entity mapped classes.

So the first thing is to create the object of datacontext and create a active connection using the SQL connection string.

DataContext objContext = new DataContext(strConnectionString);

The second thing is to get the entity collection using the table data type. This is done using the 'gettable' function of the datacontext.

Table<clsCustomerEntity> objTable = objContext.GetTable<clsCustomerEntity>()

Once we get all the data in table collection it's time to browse through the table collection and display the record.

            foreach

                (clsCustomerEntity objCustomer in objTable)
                {
                Response.Write(objCustomer.CustomerName + "<br>");
            }

You can get the above source code which is attached with this article.

Encapsulated LINQ classes with Set and Get

In the previous example we had exposed the entity class properties as public properties, which violate the basic rule of encapsulation. You can define setter and getter functions which encapsulate the private properties.
 

       [Table(Name = "Customer")] 
        public class clsCustomerEntityWithProperties 
        { 
            private int _CustomerId; 
            private string _CustomerCode; 
            private string _CustomerName; 
            [Column(DbType = "nvarchar(50)")] 
            public string CustomerCode 
            { 
                set 
                { 
                    _CustomerCode = value; 
                } 
                get 
                { 
                    return _CustomerCode; 
                } 
            } 
            [Column(DbType = "nvarchar(50)")] 
            public string CustomerName 
            { 
                set 
                { 
                    _CustomerName = value; 
                } 
                get 
                { 
                    return _CustomerName; 
                } 
            } 
            [Column(DbType = "int", IsPrimaryKey = true)] 
            public int CustomerId 
            { 
                set 
                { 
                    _CustomerId = value; 
                } 
                get 
                { 
                    return _CustomerId; 
                } 
            } 
        }

One-Many and One-One relationship

LINQ helps you define relationships using 'EntitySet' and 'EntityRef'. To understand how we can define relationships using LINQ, let's consider the below example where we have a customer who can have many addresses and every address will have phone details. In other words customer and address has one-many relationship while address and phone has one-one relationship.

4.JPG

To define one-many relationship between customer and address classes we need to use 'EntitySet' attribute. To define one-one relationship between address and phone class we need to use 'EntityRef' attribute.

5.JPG

Note :- You need to define primary key attribute for every entity class or else the mapping relationship will not work.

So below is the class entity snippet for customer class which shows how it has used 'EntitySet' to define one-many relationship with address class. Association is defined using 'Association' attribute. 'Association' attribute has three important properties storage , thiskey and otherkey. 'storage' defines the name of private variable where the address object is stored, currently it is '_CustomerAddresses'. 'ThisKey' and 'OtherKey' defines which property will define the linkage , for this instance it is 'CustomerId'. In other words both 'Customer' class and 'Address' class will have 'CustomerId' property in common.'ThisKey' defines the name of property for customer class while 'OtherKey' define the property of addresses class.

     [Table(Name = "Customer")] 
        public class clsCustomerWithAddresses 
        { 
            private EntitySet<clsAddresses> _CustomerAddresses; 
            [Association(Storage = "_CustomerAddresses", ThisKey = "CustomerId", OtherKey = "CustomerId")] 
            public EntitySet<clsAddresses> Addresses 
            { 
                set 
                { 
                    _CustomerAddresses = value
                } 
                get 
                { 
                    return _CustomerAddresses; 
                } 
            } 
        }

Below is the complete code snippet with other properties of customer class.

        [Table(Name = "Customer")] 
        public class clsCustomerWithAddresses 
        { 
            private int _CustomerId; 
            private string _CustomerCode; 
            private string _CustomerName; 
            private EntitySet<clsAddresses> _CustomerAddresses; 
            [Column(DbType = "int", IsPrimaryKey = true)] 
            public int CustomerId 
            { 
                set 
                { 
                    _CustomerId = value
                } 
                get 
                { 
                    return _CustomerId; 
                } 
            } 
            [Column(DbType = "nvarchar(50)")] 
            public string CustomerCode 
            { 
                set 
                { 
                    _CustomerCode = value
                } 
                get 
                { 
                    return _CustomerCode; 
                } 
            } 
            [Column(DbType = "nvarchar(50)")] 
            public string CustomerName 
            { 
                set 
                { 
                    _CustomerName = value
                } 
                get 
                { 
                    return _CustomerName; 
                } 
            } 
            [Association(Storage = "_CustomerAddresses", ThisKey = "CustomerId", OtherKey = "CustomerId")] 
            public EntitySet<clsAddresses> Addresses 
            { 
                set 
                { 
                    _CustomerAddresses = value
                } 
                get 
                { 
                    return _CustomerAddresses; 
                } 
            } 
        }

To define relationship between address class and phone class we need to use the 'EntityRef' syntax. So below is the code snippet which defines the relationship using 'EntityRef'. All the other properties are same except that we need to define the variable using 'EntityRef'.

       public class clsAddresses 
        { 
            private int _AddressId; 
            private EntityRef<clsPhone> _Phone; 
            [Column(DbType = "int", IsPrimaryKey = true)] 
            public int AddressId 
            { 
                set 
                { 
                    _AddressId = value
                } 
                get 
                { 
                    return _AddressId; 
                } 
            } 
            [Association(Storage = "_Phone", ThisKey = "AddressId", OtherKey = "AddressId")] 
            public clsPhone Phone 
            { 
                set 
                { 
                    _Phone.Entity = value
                } 
                get 
                { 
                    return _Phone.Entity; 
                }
            }
 
        }


Below is a complete address class with other properties. 

       public class clsAddresses 
        { 
            private int _Customerid; 
            private int _AddressId; 
            private string _Address1; 
            private EntityRef<clsPhone> _Phone; 
            [Column(DbType = "int")] 
            public int CustomerId 
            { 
                set 
                { 
                    _Customerid = value
                } 
                get 
                { 
                    return _Customerid; 
                } 
            } 
            [Column(DbType = "int", IsPrimaryKey = true)] 
            public int AddressId 
            { 
                set 
                { 
                    _AddressId = value
                } 
                get 
                { 
                    return _AddressId; 
                } 
            } 
            [Column(DbType = "nvarchar(50)")] 
            public string Address1 
            { 
                set 
                { 
                    _Address1 = value
                } 
                get 
                { 
                    return _Address1; 
                } 
            } 
            [Association(Storage = "_Phone", ThisKey = "AddressId", OtherKey = "AddressId")] 
            public clsPhone Phone 
            { 
                set 
                { 
                    _Phone.Entity = value
                } 
                get 
                { 
                    return _Phone.Entity; 
                } 
            } 
        }

Phone class which was aggregated address class.

        [Table(Name = "Phone")] 
        public class clsPhone 
        { 
            private int _PhoneId; 
            private int _AddressId; 
            private string _MobilePhone; 
            private string _LandLine; 
            [Column(DbType = "int", IsPrimaryKey = true)] 
            public int PhoneId 
            { 
                set 
                { 
                    _PhoneId = value
                } 
                get 
                { 
                    return _PhoneId; 
                } 
            } 
            [Column(DbType = "int")] 
            public int AddressId 
            { 
                set 
                { 
                    _PhoneId = value
                } 
                get 
                { 
                    return _PhoneId; 
                } 
            } 
            [Column(DbType = "nvarchar")] 
            public string MobilePhone 
            { 
                set 
                { 
                    _MobilePhone = value
                } 
                get 
                { 
                    return _MobilePhone; 
                } 
            } 
            [Column(DbType = "nvarchar")] 
            public string LandLine 
            { 
                set 
                { 
                    _LandLine = value
                } 
                get 
                { 
                    return _LandLine; 
                } 
            } 
        }

Now finally we need to consume this relationship in our ASPX client behind code.

So the first step is to create the data context object with connection initialized.
 
DataContext objContext = new DataContext(strConnectionString);

Second step is fire the query. Please note we are just firing the query for customer class. LINQ engine ensures that all the child tables data is extracted and place as per relationship defined in the entity classes.
 
var MyQuery = from objCustomer in objContext.GetTable<clsCustomerWithAddresses>() select objCustomer;

Finally we loop through the customer, loop through the corresponding addresses object and display phone details as per phone object.

       foreach (clsCustomerWithAddresses objCustomer in MyQuery) 
    { 
        Response.Write(objCustomer.CustomerName + "<br>"); 
        foreach (clsAddresses objAddress in objCustomer.Addresses) 
    {
        Response.Write("===Address:- " + objAddress.Address1 + "<br>"); 
        Response.Write("========Mobile:- " + objAddress.Phone.MobilePhone + "<br>"); 
        Response.Write("========LandLine:- " + objAddress.Phone.LandLine + "<br>"); 
    }
}

The output looks something as shown below. Every customer has multiple addresses and every address has a phone object.

6.JPG

Source code

We have also attached a source which has customer, address and phone tables. The sample code demonstrates a simple LINQ example, LINQ example with properties and relationship LINQ example with 'entityref' and 'entityset'.
 

7.JPG

You can also download Source code from top of this articles


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Shivprasad
I am currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. You can visit about my organization at www.questpond.com and also enjoy the videos uploaded for Design patter, FPA , UML , Project and lot. I am also actively involved in RFC which is a financial open source madei in C#. It has modules like accounting , invoicing , purchase , stocks etc.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
LINQtoSQL.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved