ashkufaraz
ashkufaraz

Reputation: 5307

The query results enumerated more than once

    datacontextclass dc=new datacontextclass ();
       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;

Upvotes: 2

Views: 3120

Answers (3)

Marc Gravell
Marc Gravell

Reputation: 1064134

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();

Upvotes: 6

Fredrik Mörk
Fredrik Mörk

Reputation: 158389

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);
} 

Upvotes: 2

Furqan Hameedi
Furqan Hameedi

Reputation: 4400

Change the second line of your code to

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

it shall remove the issue.

Upvotes: 1

Related Questions