开发者

The query results enumerated more than once

开发者 https://www.devze.com 2023-02-17 14:36 出处:网络
datacontextclass dc=new datacontextcla开发者_如何学JAVAss (); var news= dc.GetNewsCompany(Int64.Parse ( _idCompany));
    datacontextclass dc=new datacontextcla开发者_如何学JAVAss ();
       var news= dc.GetNewsCompany(Int64.Parse ( _idCompany));
       if (news.GetEnumerator().MoveNext())
       {
           foreach (var item in news)
           {
               drpListNews.Items.Add(item.Title);
           } 
       }

return error:{"The query results cannot be enumerated more than once."}

how can check result != null in LINQ;


Using an enumerator wildly is a bad idea - for example, it needs disposing - which you haven't done (this could lead to a SqlDataReader being left open - not good). In this case, just enumerate it. If there aren't any records, that will be trivial:

   if (news!=null)
   {
       foreach (var item in news)
       {
           drpListNews.Items.Add(item.Title);
       } 
   }

If you need the data twice, put it in a list:

   var news = (blah).ToList();


You are creating the enumerator twice. The first is by calling news.GetEnumerator(), the second one happens behind the scenes in the foreach loop. The first "check" that you make with the call to MoveNext does not seem necessary (you will not go into the foreach unless there are items to iterate over), so just skip the if statement wrapping the loop:

datacontextclass dc = new datacontextclass();
var news = dc.GetNewsCompany(Int64.Parse(_idCompany));
foreach (var item in news)
{
    drpListNews.Items.Add(item.Title);
} 


Change the second line of your code to

    var news= dc.GetNewsCompany(Int64.Parse ( _idCompany)).toList();

it shall remove the issue.

0

精彩评论

暂无评论...
验证码 换一张
取 消