LINQ to Entities无法识别方法'System.String ToString()'方法,并且此方法无法转换为存储表达式

时间:2012-10-29 11:49:30

标签: asp.net linq-to-entities asp.net-mvc-4

LINQ to Entities无法识别方法'System.String ToString()'方法,并且此方法无法转换为商店表达式。

    public ActionResult PopulateFromDB(string sidx, string sord, int page, int rows)
    {
        var context = new NerdDinnerEntities();
        var jsonData = new
        {
            total = 1,
            page = page,
            sord =sord,
            records = context.Authors.Count(),
            rows = (from n in context.Authors
                    select new
                    { AuthorId = n.AuthorId ,
                        cell = new string[] { n.AuthorId.ToString(), n.Name.ToString(), n.Location.ToString() }
                    }).ToList()
        };
        return Json(jsonData, JsonRequestBehavior.AllowGet);
    }

我正在写ToList或Toarray它不能正常工作,错误来了:

    public ActionResult PopulateFromDB(string sidx, string sord, int page, int rows)
    {
        var context = new NerdDinnerEntities();
        var jsonData = new
        {
            total = 1,
            page = page,
            sord =sord,
            records = context.Authors.Count(),
            rows = (from n in context.Authors
                    select new
                    { AuthorId = n.AuthorId ,
                        cell = new string[] { n.AuthorId.ToString(), n.Name.ToString(), n.Location.ToString() }
                    }).ToList()
        };
        return Json(jsonData,JsonRequestBehavior.AllowGet); 
    }

2 个答案:

答案 0 :(得分:0)

你应该尝试SqlFunctions.StringConvert转换它,int没有重载,所以你应该把你的数字转换成双倍或小数。

public ActionResult PopulateFromDB(string sidx, string sord, int page, int rows)
{
    var context = new NerdDinnerEntities();
    var jsonData = new
    {
        total = 1,
        page = page,
        sord =sord,
        records = context.Authors.Count(),
        rows = (from n in context.Authors
                select new
                { AuthorId = n.AuthorId ,
                  cell = new string[] { SqlFunctions.StringConvert((double)n.AuthorId), n.Name, n.Location }
                }).ToList()
    };
    return Json(jsonData,JsonRequestBehavior.AllowGet); 
}

您没有使用LinqToSql类,如果您使用的是您的代码应该可以使用,但是当您提到您正在使用LinqToEntity时,您应该使用SqlFunctions.StringConvert转换为字符串。

答案 1 :(得分:0)

从您的代码中我假设您在客户端添加自定义属性cell用于显示/存储目的。我会避免这种情况,因为您将API调用本质上与一个特定客户端耦合。我建议你只需返回所需的数据&在客户端处理它,特别是例如。

服务器

...
select new
{
    Id = n.AuthorId,
    Name = n.Name,
    Location = n.Location
}).ToList();
...

<强>客户端

var response = ...
foreach (var author in response)
{
    var cell = new string[] { author.Id.ToString(), author.Name, author.Location };
    // do something with cell
}