简体   繁体   中英

Strongly typed access to result-set from Linq Join - to display in MVC view

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM