Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumeration yielded no result?

I am trying to filter some objects using linq to enitites and I get an error telling me "Enumeration yielded no results".

on the client side I get a message like this:

The operation cannot be completed because the DbContext has been disposed

I know that these filter values should return some results but it just doesnt work, so Im guessing my query is wrong, can you help please.

var mediaChannels =
NeptuneUnitOfWork.MediaChannels
          .FindWhere(m => m.CountryID == CountryID && 
                          m.SonarMediaTypeID == MediaTypeID &&
                          m.SonarMediaTypes.SonarMediaGroupID == MediaGroupID &&
                          m.Name.Contains(search))
          .Select(m => new MediaChannelModel() {
                 ID = m.ID,
                 Name = m.Name,
                 MediaType = m.MediaType.Name,
                 Country = m.Countries.Name,
                 SubRegion = m.Countries.Lookup_SubRegions.Name,
                 Region = m.Countries.Lookup_SubRegions.Lookup_Regions.Name
      });
like image 886
Farhad-Taran Avatar asked Jul 12 '13 15:07

Farhad-Taran


2 Answers

The operation cannot be completed because the DbContext has been disposed is often seen if you send data to the client without saving the data to memory. This can be easily fixed by .ToList()-ing your query before sending it to the page

var mediaChannels = NeptuneUnitOfWork.MediaChannels
                    .Where(m => m.CountryID == CountryID
                             && m.SonarMediaTypeID == MediaTypeID &&
                             && m.SonarMediaTypes.SonarMediaGroupID == MediaGroupID
                             && m.Name.Contains(search))
                    .Select(m => new MediaChannelModel() {
                                         ID = m.ID,
                                         Name = m.Name,
                                         MediaType = m.MediaType.Name,
                                         Country = m.Countries.Name,
                                         SubRegion = m.Countries.Lookup_SubRegions.Name,
                                         Region = m.Countries.Lookup_SubRegions.Lookup_Regions.Name
                     }).ToList(); // <<-- NOTE this additional method
like image 32
NinjaNye Avatar answered Nov 11 '22 09:11

NinjaNye


My guess is that this runs just fine, then you dispose you context, then you try to access mediaChannels. The problem is that Linq uses deferred execution. Therefore, you query doesn't really execute until you enumerate mediaChannels, which is after you context is disposed.

If you don't want to use deferred execution, then add a .ToList() to the end of your query to force it to load right there.

If you want to use deferred execution, then you can't dispose of your context until a later point.

like image 119
cadrell0 Avatar answered Nov 11 '22 10:11

cadrell0