In my ASP.NET MVC Core app, I get following error when the following LINQ Query is sent to ViewModel:
Error: InvalidOperationException: Operation is not valid due to the current state of the object.
View Model:
public class StatesViewModel
{
public string StateCode { get; set; }
}
LINQ Queries:
var QryStates = from s in _context.States
where s.StateAbrv != null && s.StateAbrv != string.Empty
select new { s.StateAbrv };
var QryCustCount = (from c in ontext.Customers
join qs in QryStates on c.StateAbrv equals qs.StateAbrv
group qs by new { qs.StateAbrv } into grpStateAbrv
select new StatesViewModel{ StateCode = grpStateAbrv.Key.Statecd }).ToList();
NOTE:
select new StatesViewModel{ StateCode = grpStateAbrv.Key.Statecd }).ToList();
line of the second query. It does not occur if I replace this part with just select new { StateCode = grpStateAbrv.Key.Statecd };
But then I won't be able to send the query result to the View Model that is used in the View I'm using for displaying the second query result.QryStates
itself does return correct data.UPDATE:
In the real scenario I'm counting the number of customers per state. But to narrow down a cause of the error I've taken the count part out here for brevity of this post.