tags:

views:

129

answers:

2

This is my static query

    var results = from v in users
              join d in orders on v.UserId equals d.UserId
              join p in Products on d.ProductId equals p.ProductId
              where v.UserName.Contains(UserName)
              where v.FirstName.Equals(FirstName)
              where v.ZipCity.Equals(ZipCity)
              where v.OrderDate >= OrderDate && v.OrderDate < OrderDate
              where p.ProductName.Equals(ProductName)
              select v.Email, v.ShippingCity, v.TrackingNo;

I was looking at dynamic Linq and am trying to expand my feel on it. The above query is in a method called

GetOrder(string UserName, string FirstName, string ZipCity, DateTime OrderDate, ProductName)

Can I do this with Dynamic Linq, join to Products Table only if ProductName is not null in input parameter?

I was following this http://blog.bvsoftware.com/post/2008/02/27/How-to-create-a-Dynamic-LINQ-Query-Programmatically.aspx

+1  A: 

Take a look at the answer I gave for this question:

http://stackoverflow.com/questions/893036/best-practices-for-building-a-search-app/893072#893072

Jason Heine
Jason, how would your class handle the Joins on the different tables based on input params?
You can create an extension method off each table type. Then you can apply your filters to those tables. So you can have query from table1.Filter() join table2.Filter()
Jason Heine
+2  A: 

I think I'd use extension methods on IEnumerable instead of Dynamic LINQ.

var result = from v in users
             join d in orders on v.UserId equals d.UserId
             where v.UserName.Contains(UserName)
             where v.FirstName.Equals(FirstName)
             where v.ZipCity.Equals(ZipCity)
             where v.OrderDate >= OrderDate && v.OrderDate < OrderDate
             select v.Email, v.ShippingCity, v.TrackingNo, d.ProductId;

if (!string.IsNullOrEmpty(ProductName))
{
   result = result.Join( Products.Where( p=> p.ProductName == ProductName ),
                         d => d.ProductId,
                         p => p.ProductId,
                         (d,p) => new
                                  {
                                      d.Email,
                                      d.ShippingCity,
                                      d.TrackingNo
                                  });
}
tvanfosson