【问题标题】:enumerated more than once in linq to sql stored procedure call在 linq to sql 存储过程调用中多次枚举
【发布时间】:2017-11-18 05:58:13
【问题描述】:

我正在通过 linq to sql 调用存储过程。

var qlist = dbc.GetInfoByIDandDate(ID, aDate);  //sp call

if (qlist.Count() == 0)
{
  // error msg
}
else if (qlist.Count() > 1)
{
  // A different Error msg.
}
else
{
    GetInfoByIDandDateResult res = (GetInfoByIDandDateResult) qlist.First();
    string x = res.fieldXname;  // this is a field in the result set.
      ... and so on.
}

我已经尝试了这个的各种化身,但总是一个错误。 此迭代的错误是“查询结果不能枚举多次。”

处理这个问题的正确方法是什么?

【问题讨论】:

  • 不要多次枚举结果?
  • 字符串结果 = qlist.Count == 0 ? “错误 1”:qlist.Count == 1? “错误 2” : (GetInfoByIDandDateResult) qlist.First().fieldXname;
  • 您也可以使用 Single 代替 First,如果结果不完全一致,则会引发异常。这样你就不需要调用 Count。

标签: c# asp.net linq linq-to-sql


【解决方案1】:

当你调用 Count() 和 First() 时,实际上你每次都在枚举。

我猜这样可以解决问题:

var qlist = dbc.GetInfoByIDandDate(ID, aDate).ToList();

或者,甚至更聪明:

var qlist = dbc.GetInfoByIDandDate(ID, aDate).Take(2).ToList();

请注意,ToList() 会缓存结果,因此 Count() 和 First() 不会再次运行查询。

【讨论】:

  • 为什么是 Take(2) 而不是 Take(1)?
  • 我之前使用过 ToList() 选项,但遇到了不同的问题。会再试一次。
  • 废话。那个时候奏效了。我以前一定有其他问题。 Tx,el
  • Take(2) 因为否则 if (qlist.Count() > 1) 将始终为假
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多