Enumeration failed?

I am trying to filter out some objects using linq for enitites, and I get an error: "Enumeration did not give any results."

on the client side, I get the following message:

The operation could not be completed because the DbContext was located

I know that these filter values ​​should return some results, but it just doesn't work, so I assume my query is wrong, can you help.

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 }); 
+4
source share
2 answers

I assume this works very well, then you have the context and then try to access the mediaChannels . The problem is that Linq uses delayed execution. Therefore, the request is not executed until you list the mediaChannels , which is located after you set up the context.

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

If you want to use deferred execution, then you cannot get rid of your context to a later point.

+9
source

The operation cannot be completed because the DbContext has been disposed often observed if you send data to the client without storing the data in memory. This can be easily fixed using .ToList() answer your request 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 
+2
source

Source: https://habr.com/ru/post/1491143/


All Articles