[英]Convert to Int from String from LINQ Query field using C# for comparison (Height From)
我嘗試使用linq查詢,當我嘗試以某種方式轉換高度值時,在運行時出現錯誤。
錯誤:
LINQ to Entities無法識別方法'Int32 ToInt32(System.String)'方法,並且該方法無法轉換為商店表達式。
有沒有更好的方法來比較高度值?
case "HeightFrom":
photosquery = photosquery.Where(x => Convert.ToInt32(x.physical.BodyHeight.TrimEnd()) >= Convert.ToInt32(height));
break;
case "HeightFrom":
var h = Convert.ToInt32(height);
photosquery = photosquery.Where(x => Convert.ToInt32(x.physical.BodyHeight.TrimEnd()) >= h);
break;
EF不知道該如何翻譯最后一次轉換。 如果第一個不起作用,請嘗試int.parse(x.physical.BodyHeight.TrimEnd())
或直接投射(int)x.physical.BodyHeight.TrimEnd()
如果是我,並且有時間,我可能會在開始查詢之前將該模型映射到具有正確數據類型的另一個模型。
問題是您使用的Linq提供程序(可能來自EF)不支持Convert.ToInt32
。 此問題的快速解決方案是使用AsEnumerable
擴展方法將Linq切換為Objects
photosquery = photosquery.AsEnumerale()
.Where(x => Convert.ToInt32(x.physical.BodyHeight.TrimEnd()) >= Convert.ToInt32(height));
現在,如果BodyHeight
是一個字符串,並且您要保存一個整數,我強烈建議您盡可能更改該列的類型。 您的查詢可以完全在服務器端執行:
int value=Convert.ToInt32(height);
photosquery = photosquery.Where(x => x.physical.BodyHeight >= value);
如果您的數據不多,可以使用
case "HeightFrom": photosquery = photosquery.ToList().Where(x => Convert.ToInt32(x.physical.BodyHeight.TrimEnd()) >= Convert.ToInt32(height)); break;
但是對於繁重的數據並不能正常工作,請先加載所有數據,然后再對其進行過濾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.