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

本文详细介绍了在LINQ查询时,遇到将字符串转换为整型时出现错误的解决方法,包括两种不同的解决方案。通过实例演示了如何正确地将字符串解析为整型,并应用于查询中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、案例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()",因此该方法无法转换为存储表达式。”

解决方案一:

// 获取市级地区
public  JsonResult GetCity( string  id)
{
    
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 };
    
return  Json(city.ToList(), JsonRequestBehavior.AllowGet);
}

解决方案二:

using System.Data.Objects.SqlClient;  //在 System.Data.Entity.dll 中
// 获取市级地区
public  JsonResult GetCity( string  id)
{
    var city 
=  from c  in  db.AreaDivide  where   SqlFunctions.StringConvert(( double )c.ParentID)  ==  id  select  new  { text  =  c.AreaName, value  =  c.ID };
    
return  Json(city.ToList(), JsonRequestBehavior.AllowGet);
}

 

相关资料:

http://archive.cnblogs.com/a/1878714/

http://stackoverflow.com/questions/1228318/linq-int-to-string

http://stackoverflow.com/questions/1066760/problem-with-converting-int-to-string-in-linq-to-entities

 

转载于:https://www.cnblogs.com/linyechengwei/archive/2011/06/21/2086362.html

using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Runtime; using Autodesk.AutoCAD.Windows; using Newtonsoft.Json.Linq; using System; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace JavaScriptSamples { public class ChartCommands { private PaletteSet _chps = null; private static Document _curDoc = null; private bool _refresh = false; [DllImport( "AcJsCoreStub.crx", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Cdecl, EntryPoint = "acjsInvokeAsync")] extern static private int acjsInvokeAsync( string name, string jsonArgs ); [CommandMethod("CHART")] public void ChartPalette() { // We're storing the "launch document" as we're attaching // various event handlers to it _curDoc = Application.DocumentManager.MdiActiveDocument; // Only attach event handlers if the palette isn't already // there (in which case it will already have them) var attachHandlers = (_chps == null); _chps = Utils.ShowPalette( _chps, new Guid("F76509E7-25E4-4415-8C67-2E92118F3B84"), "CHART", "D3.js Examples", GetHtmlPathChart() ); if (attachHandlers && _curDoc != null) { AddHandlers(_curDoc); Application.DocumentManager.DocumentActivated += OnDocumentActivated; _curDoc.BeginDocumentClose += (s, e) => { RemoveHandlers(_curDoc); _curDoc = null; }; // When the PaletteSet gets destroyed we remove // our event handlers _chps.PaletteSetDestroy += OnPaletteSetDestroy; } } [JavaScriptCallback("SelectObjectsOfType")] public string SelectObjectsOfType(string jsonArgs) { // Default result is an error var res = "{\"retCode\":1}"; var doc = Application.DocumentManager.MdiActiveDocument; if (doc == null) return res; var ed = doc.Editor; //ed.SetImpliedSelection(new ObjectId[]{}); // Extract the DXF name to select from the JSON arguments var jo = JObject.Parse(jsonArgs); var dxfName = jo.Property("class").Value.ToString(); var expanded = (bool)jo.Property("expanded").Value; // We'll select all the entities of this class var tvs = new TypedValue[] { new TypedValue((int)DxfCode.Start, dxfName) }; // If the wedge is already expanded, we want to clear the // pickfirst set (so the default value is null) ObjectId[] ids = null; if (!expanded) { // Perform the selection var sf = new SelectionFilter(tvs); var psr = ed.SelectAll(sf); if (psr.Status != PromptStatus.OK) return res; // Get the results in our array ids = psr.Value.GetObjectIds(); } // Set or clear the pickfirst selection ed.SetImpliedSelection(ids); // Set the focus on the main window for the update to display // (this works fine when floating, less well when docked) Application.MainWindow.Focus(); // Return success return "{\"retCode\":0}"; } [JavaScriptCallback("GetObjectCountData")] public string GetObjectData(string jsonArgs) { var doc = Application.DocumentManager.MdiActiveDocument; if (doc == null) return "{\"retCode\":1}"; // Initialize the JSON string to return the count information var sb = new StringBuilder("{\"retCode\":0, \"result\":"); sb.Append("{\"sortOrder\":\"value-desc\",\"content\":["); using ( var tr = doc.TransactionManager.StartOpenCloseTransaction() ) { bool first = true; var ms = (BlockTableRecord)tr.GetObject( SymbolUtilityServices.GetBlockModelSpaceId(doc.Database), OpenMode.ForRead ); // Use LINQ to count the objects in the modelspace, // grouping the results by type (all done via ObjectIds, // no need to open the objects themselves) var q = from ObjectId o in ms group o by o.ObjectClass.DxfName into counts select new { Count = counts.Count(), Group = counts.Key }; // Serialize the results out to JSON foreach (var i in q) { if (!first) sb.Append(","); first = false; sb.AppendFormat( "{{\"label\":\"{0}\",\"value\":{1}}}", i.Group, i.Count ); } tr.Commit(); } sb.Append("]}}"); return sb.ToString(); } private void OnDocumentActivated( object s, DocumentCollectionEventArgs e ) { if (_chps != null && e.Document != _curDoc) { // We're going to monitor when objects get added and // erased. We'll use CommandEnded to refresh the // palette at most once per command (might also use // DocumentManager.DocumentLockModeWillChange) // The document is dead... RemoveHandlers(_curDoc); // ... long live the document! _curDoc = e.Document; AddHandlers(_curDoc); if (_curDoc != null) { // Refresh our palette by setting the flag and running // a command (could be any command, we've chosen REGEN) _refresh = true; _curDoc.SendStringToExecute( "_.REGEN ", false, false, false ); } else { acjsInvokeAsync("refpie", "{}"); } } } private void AddHandlers(Document doc) { if (doc != null) { if (doc.Database != null) { doc.Database.ObjectAppended += OnObjectAppended; doc.Database.ObjectErased += OnObjectErased; } doc.CommandEnded += OnCommandEnded; } } private void RemoveHandlers(Document doc) { if (doc != null) { if (doc.Database != null) { doc.Database.ObjectAppended -= OnObjectAppended; doc.Database.ObjectErased -= OnObjectErased; } doc.CommandEnded -= OnCommandEnded; } } private void OnObjectAppended(object s, ObjectEventArgs e) { _refresh = true; } private void OnObjectErased(object s, ObjectErasedEventArgs e) { _refresh = true; } private void OnCommandEnded(object s, CommandEventArgs e) { // Invoke our JavaScript functions to refresh the palette if (_refresh && _chps != null) { acjsInvokeAsync("refpie", "{}"); _refresh = false; } } private void OnPaletteSetDestroy(object s, EventArgs e) { // When our palette is closed, detach the various // event handlers if (_curDoc != null) { RemoveHandlers(_curDoc); _curDoc = null; } } private static Uri GetHtmlPathChart() { return new Uri(Utils.GetHtmlPath() + "chart.html"); } } }检查我这段代码
最新发布
07-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值