天天看點

LINQ to Entities 不識别方法"System.String ToString()"

一、案例1,及解決方案:

在做批量删除時,需把一串id值所對應的資料删除,調試出現問題:

Linq語句中如果使用ToString()進行類型轉換,編譯時不會報錯,但執行時會出現如下錯誤:

“LINQ to Entities 不識别方法"System.String ToString()",是以該方法無法轉換為存儲表達式。”

原因是Linq不支援ToString()函數。

可用下述方法進行轉換解決:

string source = "1,2,3,4,5";

List<int> result = new List<string>(source.Split(',')).ConvertAll(i => int.Parse(i));

注: 需引用下列命名空間

using System.Collections.Generic;

using System.Linq;

二、案例2,及解決方案:

//擷取市級地區

public JsonResult GetCity(string id)

{

    var city = from c in db.AreaDivide where c.ParentID == int.Parse(id) select new { text = c.AreaName, value = c.ID };

    return Json(city.ToList(), JsonRequestBehavior.AllowGet);

}

以上代碼也會出現如下錯誤:

解決方案一:

LINQ to Entities 不識别方法"System.String ToString()"

    int a; int.TryParse(id, out a);

    var city = from c in db.AreaDivide where c.ParentID == a select new { text = c.AreaName, value = c.ID };

LINQ to Entities 不識别方法"System.String ToString()"

解決方案二:

LINQ to Entities 不識别方法"System.String ToString()"

using System.Data.Objects.SqlClient;  //在 System.Data.Entity.dll 中

    var city = from c in db.AreaDivide where SqlFunctions.StringConvert((double)c.ParentID) == id select new { text = c.AreaName, value = c.ID };

LINQ to Entities 不識别方法"System.String ToString()"

相關資料:

<a href="http://archive.cnblogs.com/a/1878714/">http://archive.cnblogs.com/a/1878714/</a>

<a href="http://stackoverflow.com/questions/1228318/linq-int-to-string">http://stackoverflow.com/questions/1228318/linq-int-to-string</a>

<a href="http://stackoverflow.com/questions/1066760/problem-with-converting-int-to-string-in-linq-to-entities">http://stackoverflow.com/questions/1066760/problem-with-converting-int-to-string-in-linq-to-entities</a>

學習交流群:364976091

下一篇: py