3

I am having trouble figuring out how to traverse a one to many relasionship using LINQ-To-SQL in my asp.net site that uses EF 5. I have made the relationships in the class files but when I try to go from parent to child in my where clause I am not given a list of the child columns to filter on. Can anyone tell me what is wrong with my code, I am new to EF and LINQ.

Product.cs:

    public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Category Category { get; set; }
}

}

Category.cs:

    public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual IList<Product> Products { get; set; }
}

Codebehind:

            using (var db = new Compleate())
        {
            rpBooks.DataSource = (from c in db.Categories
                                  where c.Products.Name == "Books"
                                  select new
                                  {
                                      c.Name
                                  }).ToList();
        }

3 Answers3

1

Do you want all products in the books category?

from p in db.Products
where p.Category.Name == "Books"
select new
{
    p.Name
}

Or do you want to have all categories that contain products that are called called books?

from c in db.Categories
where c.Products.Contains( p => p.Name == "Books")
select new
{
    c.Name
}

BTW, if you're only selecting the name, you can skip the anonymous type in the select part...

select p.name
Arjan Einbu
  • 13,543
  • 2
  • 56
  • 59
  • Thanks, I was doing it a bit backwords in my code. YOur first code set made it work as expected. –  Mar 04 '13 at 03:07
0

Ok I had to update the codebhind to look like:

            using (var db = new Compleate())
        {
           rpBooks.DataSource = (from c in db.Categories
                              join p in db.Products on c.ID equals p.id
                              where c.Products.Name == "Books"
                              select new
                              {
                                  c.Name
                              }).ToList();

        }
-1

It should be name = c.Name it's not an issue with traversing, it's an issue with syntax, read the brief article on anonymous types here

mdubez
  • 3,024
  • 1
  • 17
  • 10
  • name = c.Name is not valid and I am trying to filter based off the Product name (in this example). –  Mar 02 '13 at 21:08