Linq dynamic queries for user search screens

前端 未结 2 380
鱼传尺愫
鱼传尺愫 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 15:45

    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%");
    
    0 讨论(0)
  • 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<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();
    }
    
    0 讨论(0)
提交回复
热议问题