简体   繁体   中英

enumerated more than once in linq to sql stored procedure call

I'm invoking a stored procedure through 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.
}

I've tried various incarnations of this, but always an error. The error with this iteration is "The query results cannot be enumerated more than once."

What is the correct way to handle this?

When you are calling Count() and First(), you are actually enumerating each time.

I'm guessing this would do the trick:

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

or, even smarter:

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

Note that ToList() caches the results so that Count() and First() doesn't run the query again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM