Thursday, March 13, 2008

One-to-Many mapping in LINQ

Thought of posting about how you can map a simple one-many reletionship in LINQ.
Lets take for an example the relationship between a country and its cities, which is one to many, one country can have many cities, If I define a class called Country and City and then ofcourse two table called Country and City,
I can map the reletionship in a simple way that looks like this

[Table]
class Country
{
[Column(IsPrimaryKey=true)]
public int CountryId{get; set;}

[Colum]
public string CountryName{get; set;}

[Association(OtherKey="CountryId")]
public EnitySet Cities{get; set;}
}

I guess the example explains it all. The Association attribute on the cities property actually
iniitiates this reletionship and you can see the return type is a EntitySet of type City.
The OtherKey property of the Association attribute is used to provide the property name on the
City class which should be comapred with the CountryId in the Country class.
The names of all the names of types in the class above exactly map to the names in the database i.e
there is a Country table and a CountryId column in the table.
Make sure to set the IsPrimaryKey=true to the correct field.

No comments:

Post a Comment