我有数据库表。它的ORM是:
public long Id { get; set; }
public System.Guid AttrId { get; set; }
public System.Guid ProdId { get; set; }
public string Value { get; set; }
public virtual Attributes Attributes { get; set; }
public virtual Products Products { get; set; }
正如您所看到的,value是一种字符串类型。我试图通过此字段获取最小值和最大值(某些值表示为double)。所以这是我的方法:
public double[] GetMaxMinVals(Guid attrId)
{
double[] res = new double[2];
using(entityContext = new SiteDBEntities())
{
res[0] = entityContext.ProductAttributes.Where(x=>x.AttrId == attrId)
.Min(x => Convert.ToDouble(x.Value));
res[1] = entityContext.ProductAttributes.Where(x => x.AttrId == attrId)
.Max(x => Convert.ToDouble(x.Value));
}
return res;
}
但我得到例外:
LINQ to Entities无法识别方法'Double ToDouble(System.String)'方法,并且此方法无法转换为商店表达式。
那么如何搜索像小数一样的字符串值?
答案 0 :(得分:2)
此处的问题是您的查询将被翻译为SQL
并在数据库上运行,而Entity Framework不知道如何将Convert.ToDouble
转换为有效的SQL代码。
因此您可以转发到double
,如下所示,稍后会转换为SQL CAST AS
语句。
res[0] = entityContext.ProductAttributes.Where(x=>x.AttrId == attrId).Min(x => (double)x.Value);
res[1] = entityContext.ProductAttributes.Where(x => x.AttrId == attrId).Max(x => (double)x.Value);
答案 1 :(得分:1)
首先,您可以将Value
转换为双倍,然后使用Max/Min
:
public double[] GetMaxMinVals(Guid attrId)
{
double[] res = new double[2];
using(entityContext = new SiteDBEntities())
{
res[0] = entityContext.ProductAttributes
.Where(x => x.AttrId == attrId)
.Select(x => x.Value)
.Cast<double>()
.Min();
}
return res;
}
答案 2 :(得分:1)
在EF Dbcontext中不支持“Convert.ToDouble”,你可以修复它:
$Graduates = "45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,73,74,75,76,84,85,86,87,88,89,91,92,93,94,95,96,98,99,100,101,103,104,105,106,107,108,109,110,111,112,113,114,117,122,123,126,127,131,135,136,137,138,139,140,142,143,146,156"; //MajorID
$tableName = $SemYearSettings->getYearSem($Enroll);
$QryFirstNursing = "SELECT *
FROM {$tableName}
WHERE {$tableName}.MajorID NOT IN ('{$Graduates}')
AND {$tableName}.Category = {$CategoryIDN}";
$resultFirstNursing = openQry($QryFirstNursing);