Linq dynamic queries for user search screens

前端 未结 2 382
鱼传尺愫
鱼传尺愫 2021-01-15 15:35

I have a database that has a user search screen that is \"dynamic\" in that I can add additional search criteria on the fly based on what columns are available in the partic

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-15 16:07

    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 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();
    }
    

提交回复
热议问题