Linq dynamic queries for user search screens

扶醉桌前 提交于 2019-12-01 09:37:22

As for your first question, you can do this using Dynamic Linq as described by Scott Gu here

var query = Northwind.Products.Where("Lastname LIKE "test%");

I'm not sure how detailed your dynamic query needs to be, but when I need to do dynamic queries, I create a class to represent filter values. Then I pass that class to a search method on my repository. If the value for a field is null then the query ignores it. If it has a value it adds the appropriate filter.

public class CustomerSearchCriteria{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string PhoneName { get; set; }
}


public IEnumberable<Customer> Search(CustomerSearchCriteria criteria){
    var q = db.Customers();

    if(criteria.FirstName != null){
        q = q.Where(c=>c.FirstName.Contains(criteria.FirstName));
    }

    if(criteria.LastName!= null){
        q = q.Where(c=>c.LastName.Contains(criteria.LastName));
    }

    if(criteria.Phone!= null){
        q = q.Where(c=>c.Phone.Contains(criteria.Phone));
    }
    return q.AsEnumerable();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!