nimi
nimi

Reputation: 5507

How to retrieve the records from more than one table which has one to many relationship?

How to retrieve the records from more than one table which has one to many relationship.

Categories[table]
CategoryId
CategoryName

Products[table]
ProductId
CategoryId
ProductName
Description

Entites

 Category[Entity]
 CategoryId
 CategoryName
 List<Product>

Product[Entity]
ProductId
ProductName
Description

So if i give categoryId, i should get the category details with list of products associated with the category.

How to do this in linq to sql?

Upvotes: 0

Views: 74

Answers (2)

Petar Petkov
Petar Petkov

Reputation: 1479

In linq to sql you get a reference property generated in each of your entities. This said if you do this:

Category cat = context.Categories.FirstOrDefault(x=>x.CategoryId == 1); //Where one is the //id of a random category
foreach(Product prd in cat.Products)
{
//do some logic here
}

you will get all the products.

Upvotes: 1

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35126

See Include for LINQ to SQL

Upvotes: 1

Related Questions