如果对象的值不是空字符串,我想构建一个能够扩展where子句条件的动态查询。这是代码
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
};
对于Filter Object,这是代码
public class Filter
{
public int UserId { get; set; }
public string FirstName { get; set;}
}
这个想法是,如果filter.FirstName不为null,它将追加像这个
的where子句public String ConditionalAttribute(Filter filter)
{
if(filter.FirstName != "")
return "&& u.First_Name = " + filter.FirstName + "";
}
有没有办法像上面的代码那样逐字段地追加where?因为我已经尝试过上面的方法而感谢
答案 0 :(得分:1)
创建尽可能多的动态术语,以便在返回IQueryable的小方法中使用。
public IQueryable ConditionalAttribute(IQueryable query, Filter filter)
{
if(filter.FirstName != "") {
query = query.Where(x => x.First_Name == filter.FirstName);
}
return query;
}
然后根据需要在初始LINQ语句之后应用它们:
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);
该语句不会运行,直到您使用.ToList()或FirstOrDefault()或类似的方式将其投影到这样,因此您可以根据需要以这种方式继续链接到查询。
答案 1 :(得分:0)
我更倾向于使用标准的C#语法而不是LINQ语法,但话说回来,我发现在加入查询时LINQ语法更优雅。
这是一种利用标准C#语法动态过滤源容器的方法,然后使用LINQ语法创建连接查询。
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
};