我有一个表格,用于跟踪我希望围绕其构建 Web API 的协议(protocol)。我希望能够使用 GET 方法来搜索表。但是,我希望参数是可选的。例如,如果我使用 GET 调用并指定 Date == 1/23/2018 以及 Status == Active 我希望它返回所有满足的协议(protocol)即使其他可能的参数可能等于 null,该标准也是如此。
我在 Controller 上使用绑定(bind)从需要类似对象协议(protocol)的 Uri 中提取。这只是 Table Agreement 的数据上下文。我已经能够让这个工作。问题来自查询。如果用户只指定两个变量,其余参数将设置为空。
如何编写 linq to SQL 查询,以便仅使用非空参数进行查询?通过可能的参数进行解析,然后根据非空值构建查询。
注意:我不希望客户端必须为所有参数指定一个值。仅与他们相关的那些,然后让 Controller /服务类将其整理出来。
Controller
namespace API.Controllers
{
public class AgreementsController : ApiController
{
private AgreementRepository agreementRepository;
public AgreementsController()
{
this.agreementRepository = new AgreementRepository();
}
public AGREEMENT[] Get([FromUri]AGREEMENT Agreement)
{
return agreementRepository.GetAgreement(Agreement);
}
}
}
服务
namespace API.Services
{
public class AgreementRepository
{
private DatabaseEntities db = new DatabaseEntities();
public AGREEMENT[] GetAgreement(AGREEMENT agmt)
{
var query = from a in db.AGREEMENTS select a;
query.Where(a => ??????);
AGREEMENT[] agreements = query.ToArray<AGREEMENT>();
return agreements;
}
}
}
编辑 我想找到一种方法来避免对参数值进行硬编码,而宁愿根据可用参数动态构建查询。这样,对表和/或数据上下文的更改将直接由该代码反射(reflect)和适当处理。
编辑 2 我对此进行了尝试,使用反射来构建字典,并尝试通过遍历字典来动态构建查询。下面的查询似乎无效,因为每个协议(protocol)都被返回。
public AGREEMENT[] GetAgreement(AGREEMENT agmt)
{
Type type = agmt.GetType();
PropertyInfo[] properties = type.GetProperties();
Dictionary<string, object> propDictionary = new Dictionary<string, object>();
foreach (PropertyInfo property in properties)
{
var propertyValue = property.GetValue(agmt, null);
if (propertyValue != null)
{
propDictionary.Add(property.Name, propertyValue);
}
}
var query = from a in db.AGREEMENTS select a;
foreach (var prop in propDictionary)
{
query.Where(A => A.GetType().GetProperty(prop.Key).GetValue(A,null) == prop.Value);
}
AGREEMENT[] agreements = query.ToArray<AGREEMENT>();
return agreements;
}
最佳答案
您可以对每个可选参数进行空检查,例如:
var query = from a in db.AGREEMENTS select a;
query = query.Where(a => a.something == mandatoryParamter);
if(optionalParameter1 != null)
{
query = query.Where(a => a.something == optionalParameter1);
}
if(optionalParameter2 != null)
{
query = query.Where(a => a.something == optionalParameter2);
}
等等
关于c# - ASP.NET 网络 API : Perform Search on Table using HTTP GET Method and Linq to SQL Dynamically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48408559/