【问题标题】:Error Object Reference Not found when Record does not found using Linq to Entity my Query attached使用 Linq to Entity my Query 未找到记录时找不到错误对象引用
【发布时间】:2019-05-23 08:06:16
【问题描述】:

我正在尝试使用 linq to entity 获取一列值。

如果没有找到记录,它必须为空。

我的代码是,

string SeqNum = Db.Visits
                    .Where(v => v.Status == 5 && v.BuildingId == 540)
                    .OrderByDescending(v => v.VisitNumber)
                    .Select(v => v.VisitNumber).FirstOrDefault().ToString();

我收到错误 Object reference not fount 因为记录不存在 id 540 如果我将其替换为 7 它有记录并且不会发生任何错误。

【问题讨论】:

    标签: sql-server asp.net-mvc linq linq-to-entities


    【解决方案1】:
    var SeqNum = Db.Visits
                    .Where(v => v.Status == 5 && v.BuildingId == 540)
                    .OrderByDescending(v => v.VisitNumber)
                    .Select(v => v.VisitNumber).FirstOrDefault();
    

    在查询返回空值时删除 .tostring()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2020-10-10
      • 2020-04-12
      • 1970-01-01
      相关资源
      最近更新 更多