我目前的情况是使用Linq to Entities执行搜索。
如果我想通过客户的参考代码进行搜索,我将使用此方法:GetClientByReference("A01")
public IQueryable<DataLayer.Client> GetClientByReference(String reference)
{
return new DataLayer.DlClient(this.Entities).GetClientByReference(reference);
}
如果我想按客户名称搜索,我将使用此方法:GetClientByName("Joe")
public IQueryable<DataLayer.Client> GetClientByName(String name)
{
return new DataLayer.DlClient(this.Entities).GetClientByName(name);
}
显然,关于可伸缩性,这非常糟糕,因为我需要将方法组合在一起,并为每个可搜索字段写一个(GetClientByDateAndReferenceAndName
??)有没有办法让它更通用?
理想情况下,我希望能够做到这样的事情:
GetClient("Reference", "A01")
GetClient("Name", "Joe")
GetClient("Reference", "A01", "Name", "Joe")
答案 0 :(得分:3)
我假设您的DataLayer.DlClient(this.Entities)
返回IQueryable<Client>
:
public IQueryable<DataLayer.Client> GetClientBy(Expression<Func<Client, bool>> filter)
{
return new DataLayer.DlClient(this.Entities).Where(filter);
}
现在你可以
var clients = GetClientBy(client => client.Name == "Joe");
var clients = GetClientBy(client => client.Reference == "A01");
var clients = GetClientBy(client => client.Reference == "A01" &&
client.Name == "Joe");