我有数据库表。它的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; }
如您所见,值是字符串类型。我正在尝试通过此字段获取最小值和最大值(某些值表示为双精度)。所以这是我的方法:
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)"方法,并且此方法无法转换为存储表达式。
那么如何搜索像小数这样的字符串值呢?
这里的问题是你的查询将被转换为SQL
并在数据库上运行,而实体框架不知道如何将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);
首先,您可以将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;
}
在 EF Dbcontext 中不支持"Convert.ToDouble",您可以修复相同的问题:
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 => (double)x.Value);
res[1] = entityContext.ProductAttributes.Where(x => x.AttrId == attrId).Max(x => (double)x.Value);
}
return res;
}