添加FirstOrDefault到我的查询
本文关键字:查询 我的 FirstOrDefault 添加 | 更新日期: 2023-09-27 18:16:39
如何添加第一个或默认到我的控制器:
public ActionResult Index(string searchString)
{
var customers = from s in db.TicketDetails
select s;
if (!String.IsNullOrEmpty(searchString))
{
//search criteria
customers = customers.Where(s => s.SupportRef.Contains(searchString));
}
return View(db.TicketDetails.ToList());
}
我需要确保我的结果只返回1条记录。如果它们返回null
,那么我需要传入假值。
确定查询返回了多少项。
- 如果大于2则返回默认值
- 如果不返回默认值。
- 如果返回项为null,则返回默认值。
- 否则你的收藏中有一个有效的物品,你返回它:
你可以这样写:
public ActionResult Index(string searchString)
{
var defaultReturnValue = //you default dummy object
if(String.IsNullOrEmpty(searchString))
return View(defaultReturnValue);
var customers = (from s in db.TicketDetails
where s.SupportRef.Contains(searchingString)
select s).Take(2).ToList(); // execute query here so not to execute it twice
return View(customers.Count > 1 ? defaultReturnValue :
customers.FirstOrDefault() ?? defaultReturnValue);
}
我已经添加了Take(2)
,所以生成的查询将占用最多2条记录,所以,在有多个记录的情况下,它仍然不会带来所有的