Monday, July 13, 2009

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.

Catch my videos for WCF, WPF, WWF, LINQ , Silverlight,Design patterns , UML and lot on

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 :-

  2. WCF FAQ series covering simple to advance concepts :-

  3. WPF and Silverlight FAQ series covering layout, animation and bindings. :-

  4. Windows work flow FAQ series covering state machines and sequential work flow in detail. :-

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.


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.

See full detail:

No comments: