views:

152

answers:

1

I am new to the MVC/Linq party (coming from Java).

I know that I can use something like the following to get strongly typed access, but what about if I want to use a join in my linq query?

public void IQueryable<Product> GetItems(int CategoryID)

{ ...linq query... }enter code here

+1  A: 

In your example, if you have used the designer to create your Linq to SQL data context, and there is a foreign key relationship between the Product and Category tables in your database, then the Category will be a property in your Product class, so there is no need to join them.

Something along the lines of the following should help (guessing property names; db is your data context):

public IQueryable<Product> GetItems(int categoryID)
{
  return db.Products.Where(p => p.Category.CategoryID == categoryID).AsQueryable();
}

Or if you are not comfortable with the lambda syntax, then the following is synonymous:

public IQueryable<Product> GetItems(int categoryID)
{
  var result = from p in db.Products
      where p.Category.CategoryID == categoryId
      select p;
  return result.AsQueryable();
}

The Product class has a Category property, providing strongly typed access to all of the properties in category. You would use something like product.Category.Name to get the category name for example.

Also, there are a plethora of good Linq to SQL tutorials out there. Try the following:

http://it-box.blogturk.net/2007/10/19/linq-to-sql-tutorial-series-by-scott-guthrie-pdf-book-format/

http://www.hookedonlinq.com/LINQtoSQL5MinuteOverview.ashx

Rhys Jones
Hi thanks for your answer. I am looking to return more than one column from the join, not just the id. I am not so bogged down with the query, I just want to know if I bring back extra (multiple) columns, will they still be strongly typed?
Dkong
OK, so if you have a set of Products, and your product class has a Category property, you will have strongly typed access to all of the properties in category. You would use something like product.Category.Name to get the category name for example. Is this what you are after?
Rhys Jones
Thanks. That answers my question. I just wasn't sure whether returning a 'product' meant that the non product properties resulting from the join would have strongly typed access.
Dkong
Great. I have added that to the answer also.
Rhys Jones