LINQ Query and ViewModel issue

时间:2016-08-31 17:03:47

标签: c# asp.net asp.net-mvc linq visual-studio-2015

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:

  1. Error occurs on 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.
  2. I've tested and verified that the first query 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.

0 个答案:

没有答案