0

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); 
    }
4

2 回答 2

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来转换为字符串。

于 2012-10-29T12:40:39.917 回答
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
}
于 2012-10-29T12:48:34.827 回答