2012-10-29 63 views
0

LINQ to Entities不识别方法'System.String ToString()'方法,并且此方法不能转换为商店表达式。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); 
    } 
+0

试着用'Convert.ToString'取代'object.ToString' –

+0

感谢您的答复我,但同样的错误是显示转换。 ToString(n.Name)作为所有字段但不变。 – Saurabhbhatt

回答

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

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 
} 
相关问题