Error LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression [duplicate]

 ̄綄美尐妖づ 提交于 2019-12-25 02:42:26

问题


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:

  1. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!