Tuesday, 4 October 2011

Writing a LINQ query with Join and Where Condition.

var products = from p in context.Products
               join c in context.Categories on p.CategoryID equals c.ID  
               join b in context.Brands on p.BrandID equals b.ID
               where c.ID==-1 || categoryIDs.Contains(c.ID.ToString()) 
               && b.ID==-1 || brandIDs.Contains(b.ID.ToString())
&& coupon.Cities=="-1" || cityIDs.Contains(cityID.ToString())
               select p.ID.ToString();
 
Here context is the EntityModelDataContext.categories(Category),brands(Brand),
products(Product) are the tables in the DB.
 
Note:You can select combination of field from different tables and create a new one as: 
 
var products = from p in context.Products
               join c in context.Categories on p.CategoryID equals c.ID  
               join b in context.Brands on p.BrandID equals b.ID
               where c.ID==-1 || categoryIDs.Contains(c.ID.ToString())
               && b.ID==-1 || brandIDs.Contains(b.ID.ToString()) 
               && coupon.Cities=="-1" || cityIDs.Contains(cityID.ToString())
               select new { p.ID.ToString(),b.BrandName,p.ProductName;}
or
Even you can create a new constructor  as select new XYZ() { fields1...,field2....} 
where XYZ is a new Model
 


No comments:

Post a Comment