Failed to return JsonResult

The following query is successful.

var tabs = ( from r in db.TabMasters orderby r.colID select new { r.colID, r.FirstName, r.LastName }) .Skip(rows * (page - 1)).Take(rows); 

Now I want to return JsonResult as

 var jsonData = new { total = (int)Math.Ceiling((float)totalRecords / (float)rows), page = page, records = totalRecords, rows = (from r in tabs select new { id = r.colID, cell = new string[] { r.FirstName, r.LastName } }).ToArray() }; return Json(jsonData, JsonRequestBehavior.AllowGet); 

But this will lead to an error: The array type 'System.String []' cannot be initialized as a result of the request. Use "System.Collections.Generic.List`1 [System.String]" instead.

What should I do to get the expected result?

+6
source share
2 answers

I suspect this is as simple as pushing the last part in an in-process request using AsEnumerable() :

 var jsonData = new { total = (int)Math.Ceiling((float)totalRecords / (float)rows), page = page, records = totalRecords, rows = (from r in tabs.AsEnumerable() select new { id = r.colID, cell = new[] { r.FirstName, r.LastName } } ).ToArray() }; return Json(jsonData, JsonRequestBehavior.AllowGet); 

You can extract this request from an initializer of an anonymous type, for clarity:

 var rows = tabs.AsEnumerable() .Select(r => new { id = r.colID, cell = new[] { r.FirstName, r.LastName }) .ToArray(); var jsonData = new { total = (int)Math.Ceiling((float)totalRecords / (float)rows), page, records = totalRecords, rows }; 
+8
source

This is because it adds LINQ to the query, which is your IQueryable tabs . Then you try to turn the LINQ expression into an SQL query, and the provider does not support the design of arrays.

You can either change the assignment of the LINQ expression to tabs to use ToList to materialize the database results right then and there, or you can add .AsEnumerable () to the LINQ expression assigned to the rows field of the anonymous type, which is your JsonResult. AsEnumerable will lower the IQueryable value to IEnumerable, which will prevent your second LINQ query from trying to query the database and just make the LINQ-to-objects call what it should be.

+1
source

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


All Articles