【问题标题】:Adding FirstOrDefault to my query?将 FirstOrDefault 添加到我的查询中?
【发布时间】:2016-11-06 19:06:02
【问题描述】:

如何先添加或默认添加到我的控制器:

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,那么我需要传入虚拟值。

【问题讨论】:

  • 明确您想要返回的内容。客户还是收藏的第一个条目?
  • 我希望用户在表单中搜索 ID,然后我的查询应该找到记录。一旦找到记录,我想在文本框中显示该 1 行值。
  • 如果searchString 为空会发生什么?那你想要什么?
  • 我想我这里有 2 个问题。我无法在文本框中显示我的值,因为查询返回了超过 1 条记录,如果它为 NULL,那么我的页面就会崩溃。!

标签: c# asp.net entity-framework linq


【解决方案1】:

确保您从查询中返回了多少项目。

  • 如果超过 2 则返回您的默认值。
  • 如果 nun 返回您的默认值。
  • 如果返回的项目为 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 条记录,因此,如果有不止一条记录,它仍然不会带来所有记录

【讨论】:

  • 感谢您的信息!我收到以下错误,因为我没有正确显示值:The model item passed into the dictionary is of type 'SignalRChat.Models.TicketDetail', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[SignalRChat.Models.TicketDetail]'。`
  • 是的,因为您的模型仍然是 IEnumerable<T> 而不是单个 T。如果你知道你只想要一个项目,就像你上面说的,然后将它从一个集合更改为单个 T
  • 我用这个修复了它:@model SignalRChat.Models.TicketDetail
  • 我相信如果找到两条记录,SingleOrDefault 会抛出 InvalidOperationException 异常(不返回 null)请参阅 msdn.microsoft.com/en-us/library/bb342451(v=vs.110).aspx
  • @LukeMcGregor - 我错了。谢谢你给我看。非常感激。更正答案
猜你喜欢
  • 1970-01-01
  • 2021-08-08
  • 2012-06-02
  • 2022-08-15
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
相关资源
最近更新 更多