首页 文章

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

提问于
浏览
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); 
    }

2 回答

  • 0

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

    Server

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

    Client

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

    你应该尝试SqlFunctions.StringConvert转换它,int没有重载,所以你应该将你的数字转换为double或小数 .

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

相关问题