You are on page 1of 9

6/7/13

One-Many and One-One relationships using LINQ to SQL - CodeProject


Sign in

Sign up for our free weekly Web Developer 9,912,506 Newsletter. members (35,172 online)

home

articles

quick answers

discussions

features

community

help
Next

Search for articles, questions, tips

Articles Platforms, Frameworks & Libraries LINQ General

Article Browse Code Stats Revisions (4) Alternatives Comments & Discussions (10)

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


By Shivprasad koirala , 5 Jul 2009
3.94 (15 votes)

About Article
One-many and one-one relationships using LINQ to SQL. Type Licence Article CPOL 30 Jun 2009 47,983 693 49 times

Download source code - 1.02 MB

First Posted Views Downloads Bookmarked

Table of contents
Introduction Previous LINQ, Silverlight, WCF, WPF, and WWF articles Simplest LINQ to SQL example Encapsulated LINQ classes with Set and Get One-Many and One-One relationships Source code

VS.NET2003 VS2005 VS2008 C# ASP.NET SQL , +

Introduction
In this article, we will start with a basic LINQ to SQL example and then see how we can implement onemany and one-one relationships using E n t i t y r e f and E n t i t y S e t . I have attached a source code which demonstrates this in a practical manner. Catch my videos for WCF, WPF, WWF, LINQ, Silverlight, Design Patterns, UML, and a lot on http://www.questpond.com.

Previous LINQ, Silverlight, WCF, WPF, and WWF articles


Below are some of my old articles which you would want to refer to in case you are not acquainted with .NET 3.5 basic concepts. 1. This article talks about a complete three tier implementation using LINQ: http://www.codeproject.com/KB/aspnet/SaltAndPepper.aspx 2. WCF FAQ series covering simple to advanced concepts: http://www.codeproject.com/KB/aspnet/WCF.aspx 3. WPF and Silverlight FAQ series covering layout, animation, and bindings: http://www.codeproject.com/KB/WPF/WPFSilverLight.aspx 4. Windows workflow FAQ series covering state machines and sequential workflow in detail: http://www.codeproject.com/KB/WF/WWF.aspx

Simplest LINQ to SQL example


Lets first start with a simple LINQ to SQL example and then we will try to understand how we can establish relationships in LINQ entities.

Step 1: Define Entity classes using LINQ


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

Top News
Old Japanese Man Creates Amazing Art Using Excel (Wait, Excel?)
Get the Insider News free each

www.codeproject.com/Articles/37784/One-Many-and-One-One-relationship-using-LINQ-to-SQ

1/9

6/7/13

One-Many and One-One relationships using LINQ to SQL - CodeProject


morning.

Related Videos

Brian Harry TechEd Interview TFS 2013 and VS 2013

Introduction to TestDriven Development

Related Articles
Matrix Multiplication in C# Creating animations with Dundas Chart for ASP.NET

In LINQ, we need to first define these entity classes using attribute mappings. You need to import the S y s t e m . D a t a . L i n q . M a p p i n g namespace to get attributes for mapping. Below is a code snippet which shows how the T a b l e attribute maps the class with the database table name Customer and how the C o l u m n attributes help mapping properties with table columns.
Collapse | Copy Code

Smarter Data Labels with Dundas Chart SmartLabels Understanding Chart Areas with Dundas Chart for .NET Add "Select All" to parameter lists in SQL Reporting Using screensavers inside the Windows Media Player Making Sense of Geographic Data with Dundas Map and AJAX SmartLink Create data-driven applications with the Hera Application Framework Towards the self-documenting database: extended properties Accessibility audit vs. accessibility testing Digital Signatures and PDF Documents Color Scale Filter WMP Power Hour APP Merge Landscape and Portrait PDFs using ASP.NET How to conduct an SMS survey using a cell phone connected SMS gateway and MS Access Using Barcodes in Documents Best Practices How to Retrieve EMC Centera Cluster/Pool Capabilities "Hey! Is That My Car? How to Sharpen a QuickBird Satellite Image Using DotImage" Integrate your SharePoint environment into the open standards-based WebSphere Portal platform using the Visual Studio IDE VBScript / Excel 2007 - An easy way to access DBF files

[ T a b l e ( N a m e=" C u s t o m e r " ) ] p u b l i cc l a s sc l s C u s t o m e r E n t i t y W i t h P r o p e r t i e s { p r i v a t ei n t_ C u s t o m e r I d ; p r i v a t es t r i n g_ C u s t o m e r C o d e ; p r i v a t es t r i n g_ C u s t o m e r N a m e ; [ C o l u m n ( D b T y p e=" n v a r c h a r ( 5 0 ) " ) ] p u b l i cs t r i n gC u s t o m e r C o d e { s e t { _ C u s t o m e r C o d e=v a l u e ; } g e t { r e t u r n_ C u s t o m e r C o d e ; } } [ C o l u m n ( D b T y p e=" n v a r c h a r ( 5 0 ) " ) ] p u b l i cs t r i n gC u s t o m e r N a m e { s e t { _ C u s t o m e r N a m e=v a l u e ; } g e t { r e t u r n_ C u s t o m e r N a m e ; } } [ C o l u m n ( D b T y p e=" i n t " ,I s P r i m a r y K e y=t r u e ) ] p u b l i ci n tC u s t o m e r I d { s e t { _ C u s t o m e r I d=v a l u e ; } g e t { r e t u r n_ C u s t o m e r I d ; } }

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

www.codeproject.com/Articles/37784/One-Many-and-One-One-relationship-using-LINQ-to-SQ

2/9

6/7/13

One-Many and One-One relationships using LINQ to SQL - CodeProject

Step 2: Using the DataContext to bind the table data with the entity objects
The second step is to use the D a t a C o n t e x t object of LINQ to fill your entity objects. D a t a C o n t e x tacts like a mediator between database objects and your LINQ entity mapped classes.

The first thing is to create an object of D a t a C o n t e x t and create an active connection using the SQL connection string.
Collapse | Copy Code

D a t a C o n t e x to b j C o n t e x t=n e wD a t a C o n t e x t ( s t r C o n n e c t i o n S t r i n g ) ;

The second thing is to get the entity collection using the T a b l edata type. This is done using the G e t T a b l e function of the D a t a C o n t e x t .
Collapse | Copy Code

T a b l e < c l s C u s t o m e r E n t i t y >o b j T a b l e=o b j C o n t e x t . G e t T a b l e < c l s C u s t o m e r E n t i t y > ( ) ;

Once we get all the data in table collection, its time to browse through the table collection and display the records.
Collapse | Copy Code

f o r e a c h( c l s C u s t o m e r E n t i t yo b j C u s t o m e ri no b j T a b l e ) { R e s p o n s e . W r i t e ( o b j C u s t o m e r . C u s t o m e r N a m e+" < b r > " ) ; }

You can get the above source code from the download 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 violates the basic rule of encapsulation. You can define setter and getter functions which encapsulate the private properties.
Collapse | Copy Code

[ T a b l e ( N a m e=" C u s t o m e r " ) ] p u b l i cc l a s sc l s C u s t o m e r E n t i t y W i t h P r o p e r t i e s { p r i v a t ei n t_ C u s t o m e r I d ; p r i v a t es t r i n g_ C u s t o m e r C o d e ; p r i v a t es t r i n g_ C u s t o m e r N a m e ; [ C o l u m n ( D b T y p e=" n v a r c h a r ( 5 0 ) " ) ] p u b l i cs t r i n gC u s t o m e r C o d e { s e t { _ C u s t o m e r C o d e=v a l u e ; } g e t { r e t u r n_ C u s t o m e r C o d e ; } } [ C o l u m n ( D b T y p e=" n v a r c h a r ( 5 0 ) " ) ] p u b l i cs t r i n gC u s t o m e r N a m e

www.codeproject.com/Articles/37784/One-Many-and-One-One-relationship-using-LINQ-to-SQ

3/9

6/7/13
{ s e t { } g e t { } }

One-Many and One-One relationships using LINQ to SQL - CodeProject

_ C u s t o m e r N a m e=v a l u e ;

r e t u r n_ C u s t o m e r N a m e ;

[ C o l u m n ( D b T y p e=" i n t " ,I s P r i m a r y K e y=t r u e ) ] p u b l i ci n tC u s t o m e r I d { s e t { _ C u s t o m e r I d=v a l u e ; } g e t { r e t u r n_ C u s t o m e r I d ; } }

One-Many and One-One relationships


LINQ helps you define relationships using E n t i t y S e tand E n t i t y R e f . To understand how we can define relationships using LINQ, lets 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 a onemany relationship while address and phone has a one-one relationship.

To define a one-many relationship between the customer and address classes, we need to use the E n t i t y S e t attribute. To define a one-one relationship between the address and phone class, we need to use the E n t i t y R e f attribute.

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

www.codeproject.com/Articles/37784/One-Many-and-One-One-relationship-using-LINQ-to-SQ

4/9

6/7/13

One-Many and One-One relationships using LINQ to SQL - CodeProject


Shown below is the class entity snippet for the customer class which shows how it has used E n t i t y S e tto define one-many relationship with the address class. Association is defined using the A s s o c i a t i o n attribute. The A s s o c i a t i o n attribute has three important properties: s t o r a g e ,t h i s k e y , and o t h e r k e y . s t o r a g e defines the name of the private variable where the address object is stored. Currently it is _ C u s t o m e r A d d r e s s e s .T h i s K e y and O t h e r K e ydefine which property will define the linkage; for this instance, it is C u s t o m e r I d . In other words, both the C u s t o m e r class and the A d d r e s sclass will have a C u s t o m e r I d property in common. T h i s K e y defines the name of the property for the C u s t o m e r class while O t h e r K e y defines the property of the addresses class.
Collapse | Copy Code

[ T a b l e ( N a m e=" C u s t o m e r " ) ] p u b l i cc l a s sc l s C u s t o m e r W i t h A d d r e s s e s { p r i v a t eE n t i t y S e t < c l s A d d r e s s e s >_ C u s t o m e r A d d r e s s e s ; [ A s s o c i a t i o n ( S t o r a g e=" _ C u s t o m e r A d d r e s s e s " , T h i s K e y = " C u s t o m e r I d " ,O t h e r K e y=" C u s t o m e r I d " ) ] p u b l i cE n t i t y S e t < c l s A d d r e s s e s >A d d r e s s e s { s e t { _ C u s t o m e r A d d r e s s e s=v a l u e ; } g e t { r e t u r n_ C u s t o m e r A d d r e s s e s ; } }

Below is the complete code snippet with other properties of the customer class:
Collapse | Copy Code

[ T a b l e ( N a m e=" C u s t o m e r " ) ] p u b l i cc l a s sc l s C u s t o m e r W i t h A d d r e s s e s { p r i v a t ei n t_ C u s t o m e r I d ; p r i v a t es t r i n g_ C u s t o m e r C o d e ; p r i v a t es t r i n g_ C u s t o m e r N a m e ; p r i v a t eE n t i t y S e t < c l s A d d r e s s e s >_ C u s t o m e r A d d r e s s e s ; [ C o l u m n ( D b T y p e = " i n t " , I s P r i m a r y K e y = t r u e ) ] p u b l i ci n tC u s t o m e r I d { s e t { _ C u s t o m e r I d=v a l u e ; } g e t { r e t u r n_ C u s t o m e r I d ; } } [ C o l u m n ( D b T y p e=" n v a r c h a r ( 5 0 ) " ) ] p u b l i cs t r i n gC u s t o m e r C o d e { s e t { _ C u s t o m e r C o d e=v a l u e ; } g e t { r e t u r n_ C u s t o m e r C o d e ; } } [ C o l u m n ( D b T y p e=" n v a r c h a r ( 5 0 ) " ) ] p u b l i cs t r i n gC u s t o m e r N a m e { s e t { _ C u s t o m e r N a m e=v a l u e ; } g e t { r e t u r n_ C u s t o m e r N a m e ; } } [ A s s o c i a t i o n ( S t o r a g e=" _ C u s t o m e r A d d r e s s e s " , T h i s K e y = " C u s t o m e r I d " ,O t h e r K e y=" C u s t o m e r I d " ) ] p u b l i cE n t i t y S e t < c l s A d d r e s s e s >A d d r e s s e s { s e t { _ C u s t o m e r A d d r e s s e s=v a l u e ; } g e t { r e t u r n_ C u s t o m e r A d d r e s s e s ; } }

To define the relationship between the address class and the phone class, we need to use the E n t i t y R e f

www.codeproject.com/Articles/37784/One-Many-and-One-One-relationship-using-LINQ-to-SQ

5/9

6/7/13

One-Many and One-One relationships using LINQ to SQL - CodeProject


syntax. So below is the code snippet which defines the relationship using E n t i t y R e f . All the other properties are same except that we need to define the variable using E n t i t y R e f .
Collapse | Copy Code

p u b l i cc l a s sc l s A d d r e s s e s { p r i v a t ei n t_ A d d r e s s I d ; p r i v a t eE n t i t y R e f < c l s P h o n e >_ P h o n e ; [ C o l u m n ( D b T y p e=" i n t " ,I s P r i m a r y K e y=t r u e ) ] p u b l i ci n tA d d r e s s I d { s e t { _ A d d r e s s I d=v a l u e ; } g e t { r e t u r n_ A d d r e s s I d ; } } [ A s s o c i a t i o n ( S t o r a g e=" _ P h o n e " , T h i s K e y=" A d d r e s s I d " ,O t h e r K e y=" A d d r e s s I d " ) ] p u b l i cc l s P h o n eP h o n e { s e t { _ P h o n e . E n t i t y=v a l u e ; } g e t { r e t u r n_ P h o n e . E n t i t y ; } }

Below is a complete address class with other properties:


Collapse | Copy Code

p u b l i cc l a s sc l s A d d r e s s e s { p r i v a t ei n t_ C u s t o m e r i d ; p r i v a t ei n t_ A d d r e s s I d ; p r i v a t es t r i n g_ A d d r e s s 1 ; p r i v a t eE n t i t y R e f < c l s P h o n e >_ P h o n e ; [ C o l u m n ( D b T y p e = " i n t " ) ] p u b l i ci n tC u s t o m e r I d { s e t { _ C u s t o m e r i d=v a l u e ; } g e t { r e t u r n_ C u s t o m e r i d ; } } [ C o l u m n ( D b T y p e=" i n t " ,I s P r i m a r y K e y=t r u e ) ] p u b l i ci n tA d d r e s s I d { s e t { _ A d d r e s s I d=v a l u e ; } g e t { r e t u r n_ A d d r e s s I d ; } } [ C o l u m n ( D b T y p e=" n v a r c h a r ( 5 0 ) " ) ] p u b l i cs t r i n gA d d r e s s 1 { s e t { _ A d d r e s s 1=v a l u e ; } g e t { r e t u r n_ A d d r e s s 1 ; } } [ A s s o c i a t i o n ( S t o r a g e=" _ P h o n e " , T h i s K e y=" A d d r e s s I d " ,O t h e r K e y=" A d d r e s s I d " ) ] p u b l i cc l s P h o n eP h o n e { s e t { _ P h o n e . E n t i t y=v a l u e ; } g e t { r e t u r n_ P h o n e . E n t i t y ; } } }

The phone class which is aggregated with the address class:


Collapse | Copy Code

www.codeproject.com/Articles/37784/One-Many-and-One-One-relationship-using-LINQ-to-SQ

6/9

6/7/13

One-Many and One-One relationships using LINQ to SQL - CodeProject


[ T a b l e ( N a m e=" P h o n e " ) ] p u b l i cc l a s sc l s P h o n e { p r i v a t ei n t_ P h o n e I d ; p r i v a t ei n t_ A d d r e s s I d ; p r i v a t es t r i n g_ M o b i l e P h o n e ; p r i v a t es t r i n g_ L a n d L i n e ; [ C o l u m n ( D b T y p e=" i n t " ,I s P r i m a r y K e y=t r u e ) ] p u b l i ci n tP h o n e I d { s e t { _ P h o n e I d=v a l u e ; } g e t { r e t u r n_ P h o n e I d ; } } [ C o l u m n ( D b T y p e=" i n t " ) ] p u b l i ci n tA d d r e s s I d { s e t { _ P h o n e I d=v a l u e ; } g e t { r e t u r n_ P h o n e I d ; } } [ C o l u m n ( D b T y p e=" n v a r c h a r " ) ] p u b l i cs t r i n gM o b i l e P h o n e { s e t { _ M o b i l e P h o n e=v a l u e ; } g e t { r e t u r n_ M o b i l e P h o n e ; } } [ C o l u m n ( D b T y p e=" n v a r c h a r " ) ] p u b l i cs t r i n gL a n d L i n e { s e t { _ L a n d L i n e=v a l u e ; } g e t { r e t u r n_ L a n d L i n e ; } }

Now finally we need to consume this relationship in our ASPX client behind code: The first step is to create the data context object with the connection initialized:
Collapse | Copy Code

D a t a C o n t e x to b j C o n t e x t=n e wD a t a C o n t e x t ( s t r C o n n e c t i o n S t r i n g ) ;

The second step is firing the query. Please note that we are just firing the query for the customer class. The LINQ engine ensures that all child table data is extracted and placed as per the relationships defined in the entity classes.
Collapse | Copy Code

v a rM y Q u e r y=f r o mo b j C u s t o m e ri no b j C o n t e x t . G e t T a b l e < c l s C u s t o m e r W i t h A d d r e s s e s > ( ) s e l e c to b j C u s t o m e r ;

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

f o r e a c h( c l s C u s t o m e r W i t h A d d r e s s e so b j C u s t o m e ri nM y Q u e r y ) { R e s p o n s e . W r i t e ( o b j C u s t o m e r . C u s t o m e r N a m e+" < b r > " ) ; f o r e a c h( c l s A d d r e s s e so b j A d d r e s si no b j C u s t o m e r . A d d r e s s e s ) { R e s p o n s e . W r i t e ( " = = = A d d r e s s : -"+o b j A d d r e s s . A d d r e s s 1+" < b r > " ) ; R e s p o n s e . W r i t e ( " = = = = = = = = M o b i l e : -"+o b j A d d r e s s . P h o n e . M o b i l e P h o n e+" < b r > " ) ; R e s p o n s e . W r i t e ( " = = = = = = = = L a n d L i n e : -"+ o b j A d d r e s s . P h o n e . L a n d L i n e+" < b r > " ) ; } }

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

www.codeproject.com/Articles/37784/One-Many-and-One-One-relationship-using-LINQ-to-SQ

7/9

6/7/13

One-Many and One-One relationships using LINQ to SQL - CodeProject

Source code
We have also attached a source which has the customer, address, and phone tables. The sample code demonstrates a simple LINQ example, LINQ example with properties, and relationship LINQ example with e n t i t y r e f and e n t i t y s e t .

License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author


Shivprasad koirala
Architect http://www.questpond.com India

www.codeproject.com/Articles/37784/One-Many-and-One-One-relationship-using-LINQ-to-SQ

8/9

6/7/13

One-Many and One-One relationships using LINQ to SQL - CodeProject

I am a Microsoft MVP for ASP/ASP.NET and 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. Do visit my site for .NET, C# , design pattern , WCF , Silverlight , LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server training and Interview questions and answers

Article Top

Like

Tw eet

Sign Up to vote Poor

Excellent

Vote

Comments and Discussions


Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'. You must Sign In to use this message board. Search this forum Profile popups Spacing Relaxed Noise Medium Layout Normal Per page 50 Go Update

First Prev Next

Address and Phone can be one-to-many relationship My vote of 4 How to acheive same thing w/ a stored procedure How to acheive same thin w/ a stored procedure My vote of 5 Entity Relationship using XML mapping file ... Problem while getting the records passing parameters.. [modified] Hi Re: Hi Re: Hi
Last Visit: 31 Dec '99 - 18:00 General News Last Update: 6 Jun '13 - 16:39 Suggestion Question Bug

onmyway133

23 Oct '12 - 21:46

Armando de la Torre mbcvamsidhar

26 Jun '12 - 11:09 3 May '11 - 6:07

mbcvamsidhar Pravin Patil, Mumbai rjschweiger vurugonda

3 May '11 - 6:07 26 Jan '11 - 4:18 1 Oct '09 - 14:01 30 Jul '09 - 9:16

prasad02 Shivprasad koirala vurugonda

1 Jul '09 - 3:30 1 Jul '09 - 4:04 30 Jul '09 - 9:14 Refresh 1

Answer

Joke

Rant

Admin
Article Copyright 2009 by Shivprasad koirala Everything else Copyright CodeProject, 1999-2013 Terms of Use

Permalink | Advertise | Privacy | Mobile Web04 | 2.6.130603.1 | Last Updated 6 Jul 2009

Layout: fixed | fluid

www.codeproject.com/Articles/37784/One-Many-and-One-One-relationship-using-LINQ-to-SQ

9/9

You might also like