减少linq查询以进行过滤

时间:2014-04-21 11:31:23

标签: c# sql wpf linq entity-framework

我有一个包含3个文本框的视图,这些文本框绑定到ViewModel SupplierNameContactAddress中的属性以及一个绑定到ViewModel中SearchCommand属性的按钮。

我的要求是根据上述属性过滤Supplier条记录。我使用了EntityFramework。

用户可以输入任何上述文本框,这些文本框会导致我编写9个不同的查询。 例如,如果用户仅在SupplierName文本框上输入数据,那么我需要以SupplierName作为参数运行一个查询。如果用户输入SupplierNameContact文本框,那么我需要运行另一个查询。等等。

这是我的代码:

public IEnumerable<Model.Supplier> GetAllSuppliersBySearch(string nameMatch, string contactMatch, string phoneMatch)
    {

        if(nameMatch!=null)
        {
             var q = from f in Context.Suppliers
                where f.SupplierName==nameMatch 
                select f;
        }
        else if(contactMatch!=null)
        {
             var q = from f in Context.Suppliers
                where  f.ContactName==contactMatch 
                select f;
        }
        else if(phoneMatch!=null)
        {
            var q = from f in Context.Suppliers
                where  f.ContactName==contactMatch 
                select f;
        }

        return q.AsEnumerable();
    }

如何使用一个查询或以任何优化方式完成此操作,而不是编写多个查询?

1 个答案:

答案 0 :(得分:9)

使用lambda语法撰写查询:

IQueryable<Supplier> query = Context.Suppliers;

if (!String.IsNullOrEmpty(nameMatch))
   query = query.Where(s => s.SupplierName == nameMatch);

if (!String.IsNullOrEmpty(contactMatch))
   query = query.Where(s => s.ContactName == contactMatch);

// etc

return query.AsEnumerable();

另一个选择是为查询添加参数检查条件

var query = 
   from s in Context.Suppliers
   where (String.IsNullOrEmpty(nameMatch) || s.SupplierName == nameMatch) &&
         (String.IsNullOrEmpty(contactMatch) || s.ContactName == contactMatch)
         // etc
   select s;