【发布时间】:2015-03-15 03:53:33
【问题描述】:
我一直在使用路由和可选参数,但我遇到了一个问题,无论我从数据库中得到什么结果。这是我在控制器中的方法:
[Route("{companyID:int}/contact/{uid?}")]
[HttpGet]
public IQueryable GetCompanyContactsByID(int companyID, Guid? uid = null)
{
IQueryable<vwCompanyContact> contact = coreDB.vwCompanyContacts.Where(con => con.IDCompany == companyID);
if (uid != null)
contact = contact.Where(con => con.CatalogNumber == uid);
return contact;
}
所以基本上如果打电话 (http://localhost:21598/DAL/api/company/100/contact/) 我会得到公司 100 的所有联系人的列表。然后如果我打电话 (http://localhost:21598/DAL/api/company/100/contact/64077706-b7c9-e411-825d-28b2bd14ba94666) 我只会得到一个与 GUID 匹配的记录。但是,如果我打电话给 (http://localhost:21598/DAL/api/company/100/contact/marryhadalittlelamb),我会再次获得所有联系人的列表。
我希望收到一个空的结果集或一条回复说没有找到结果的消息。我不确定如何解决这个问题,因为我对 C# 和 Linq 还是很陌生。
这是我最终得到的代码:
[Route("{companyID:int}/contact/{uid?}")]
[HttpGet]
public IHttpActionResult GetCompanyContactByID(int compantID, string uid = null)
{
IQueryable<vwCompanyContact> contact
= coreDB.vwCompanyContacts.Where(con => con.IDCompany == companyID);
if (!string.IsNullOrEmpty(uid))
{
Guid uidValue;
if (Guid.TryParse(uid, out uidValue))
contact = contact.Where(con => con.CatalogNumber == uidValue);
else
return StatusCode(HttpStatusCode.NoContent);;
}
return Ok(contact);
}
【问题讨论】:
标签: c# linq entity-framework asp.net-web-api