问题
I am working with MVC4 , Entityframewor and Jqgrid, when am fetching data from Database , i stucked with this error.Many of you said populate the id field to anothe var , but i a not getting where exactly to write it, and my Id field in Database is of Integer. so please do help me. u.Id is a Id field which i am accessing from EF, It showing this error. what is the alternate way, and where to put the new code. My Controller looks like
public JsonResult GetUserDetails(string sidx="Id", string sord="asc", int page=1, int rows=5)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = db.Users.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var userdata = db.Users.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (from u in userdata
select new
{
i = u.Id,
cell = new string[]{**u.Id.ToString()**, u.Name,u.Designation,u.City}
//cell = new string[] { "", "", "", "" }
}).ToArray()
};
return Json(jsonData);
}
I am Working this from past a day, and not getting relief from this .
回答1:
Method ToString() cannot be translated to SQL query. So you have several options:
You can get full entity userdata from db and map it to string array in .net code:
var userdata = db.Users.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize).AsEnumerable(); var jsonData = new { total = totalPages, page, records = totalRecords, rows = ( from u in userdata select new { i = u.Id, cell = new string[]{**u.Id.ToString()**, u.Name,u.Designation,u.City} //cell = new string[] { "", "", "", "" } }).ToArray() };
2.You can use two Select()
, first to get data from db, second to map it to your string array:
var userdata = db.Users.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize).Select(u=>new{u.Id, u.Name, u.Designation, u.City});
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from u in userdata.AsEnumerable()
select new
{
i = u.Id,
cell = new string[]{u.Id.ToString(), u.Name,u.Designation,u.City}
}).ToArray()
};
来源:https://stackoverflow.com/questions/21825378/error-linq-to-entities-does-not-recognize-the-method-system-string-tostring