【发布时间】:2014-06-05 11:12:32
【问题描述】:
我有一个视图,其中包含 3 个文本框,它们绑定到 ViewModel SupplierName、Contact、Address 中的属性和一个绑定到我的 ViewModel 中 SearchCommand 属性的按钮。
我的要求是根据上述属性过滤Supplier 记录。我使用了 EntityFramework。
用户可以输入任何上述文本框,这会导致我编写 9 个不同的查询。
例如,如果用户仅在 SupplierName 文本框上输入数据,那么我需要以 SupplierName 作为参数运行一个查询。如果用户输入 SupplierName 和 Contact 文本框,那么我需要运行另一个查询。以此类推。
这是我的代码:
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();
}
如何用一个查询或以任何优化的方式来完成此任务,而不是编写多个查询?
【问题讨论】:
标签: c# sql wpf linq entity-framework