Reputation: 183
I want to build a dynamic query that able to extend the where clause condition if the value of the object is not empty string. Here is the code
public IEnumerable<Filter> GetFilter(Filter filter)
{
var y = ConditionalAttribute(filter);
var query =
from sub in Subscriptions
join u in Users
on sub.UserID equals u.Id
join od in Order_Details1
on sub.OD_Id equals od.OD_Id
join p in Products
on od.ProductId equals p.ProductId
where p.Type == "Testing" + y
select new Filter
{
//do something
};
for the Filter Object, here is the code
public class Filter
{
public int UserId { get; set; }
public string FirstName { get; set;}
}
the idea is if the filter.FirstName is not null it will append the where clause like this
public String ConditionalAttribute(Filter filter)
{
if(filter.FirstName != "")
return "&& u.First_Name = " + filter.FirstName + "";
}
Is there any way to append where clause by string like the code above? Because I've tried the approach above and it fails thanks
Upvotes: 2
Views: 1120
Reputation: 45272
I tend to prefer using standard C# syntax rather than the LINQ syntax, but, having said that, I find that LINQ syntax is more elegant when it comes to joining queries.
Here's an approach which utilizes the standard C# syntax to dynamically filter the source containers, then uses LINQ syntax to create the joining query.
public IEnumerable<Filter> GetFilter(Filter filter)
{
var y = ConditionalAttribute(filter);
IEnumerable<User> filteredUsers = Users;
if(!string.IsNullOrEmpty(filter.FirstName))
{
filteredUsers = filteredUsers.Where(u => u.First_Name == filter.FirstName);
}
var query =
from sub in Subscriptions
join u in filteredUsers
on sub.UserID equals u.Id
join od in Order_Details1
on sub.OD_Id equals od.OD_Id
join p in Products
on od.ProductId equals p.ProductId
where p.Type == "Testing" + y
select new Filter
{
//do something
};
Upvotes: 0
Reputation: 6373
Create as many dynamic terms as you want to use in small methods that return an IQueryable.
public IQueryable ConditionalAttribute(IQueryable query, Filter filter)
{
if(filter.FirstName != "") {
query = query.Where(x => x.First_Name == filter.FirstName);
}
return query;
}
then apply them after the initial LINQ statement as you require:
public IEnumerable<Filter> GetFilter(Filter filter)
{
var query =
from sub in Subscriptions
join u in Users
on sub.UserID equals u.Id
join od in Order_Details1
on sub.OD_Id equals od.OD_Id
join p in Products
on od.ProductId equals p.ProductId
where p.Type == "Testing"
select new Filter
{
//do something
};
query = ConditionalAttribute(query, filter);
The statement isn't going to run until you project it into by using .ToList() or FirstOrDefault() or something like that so you can keep chaining onto query in this way as many times as you need.
Upvotes: 1