Select Columns From Multiple Tables Using LINQ

From Northwind database, to show all available products it needs to select values from multiple tables because in Products table there are two columns – CategoryID and SupplierID which are referenced from Category and Suppliers tables. There are more then one options to do this but I use below way to select from multiple tables and bind to grid.
First of all create a class and create properties, ProductID, ProductName, CompanyName, CategoryName, UnitPrice. These are the properties which I want to show in grid.
public class AvailableProducts
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string CompanyName { get; set; }
public string CategoryName { get; set; }
public decimal UnitPrice { get; set; }
}

Now, write below function in data access layer:
public List<AvailableProducts> GetAllAvailableProducts()
{
var linqAllProducts = from p in NorthwindEntity.Products
from c in NorthwindEntity.Categories
from s in NorthwindEntity.Suppliers
where p.CategoryID == c.CategoryID
&& p.SupplierID == s.SupplierID
select new AvailableProducts
{
ProductID = p.ProductID,
ProductName = p.ProductName,
CategoryName = c.CategoryName,
CompanyName = s.CompanyName,
UnitPrice = p.UnitPrice.Value
};

return linqAllProducts.ToList();

}

Bind above result to grid on web page.

Using this option I can get typed object in my web page and I can read values by accessing it’s properties. That’s all for today, hope this will help you in your project.

Comments

  1. Good Example......y dont't you use include method... var linqAllProducts = NorthwindEntity.Products.include("Categories").include("Suppliers").select new AvailableProducts
    {
    ProductID = p.ProductID,
    ProductName = p.ProductName,
    CategoryName = c.CategoryName,
    CompanyName = s.CompanyName,
    UnitPrice = p.UnitPrice.Value
    };

    ReplyDelete

Post a Comment

Popular posts from this blog

Lambda Expressions In Entity Framework

LINQ To Entity Framework Tutorial