[英]MIN and MAX value by string in Entity Framework
I have database table. 我有数据库表。 The ORM for it is: 它的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; }
As you can see value is a string type. 如您所见,值是字符串类型。 I'm trying to get min and max values by this field (some values represented as double). 我正在尝试通过此字段获取最小值和最大值(某些值表示为double)。 So here is my method for this: 所以这是我的方法:
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;
}
But I getting exception: 但我得到例外:
LINQ to Entities does not recognize the method 'Double ToDouble(System.String)' method, and this method cannot be translated into a store expression. LINQ to Entities无法识别方法'Double ToDouble(System.String)',并且该方法无法转换为商店表达式。
So how can I search for a string value like a decimal? 那么,如何搜索类似于小数的字符串值?
The problem here is your query will be translated into SQL
and run on the database, and Entity Framework doesn't know how to translate Convert.ToDouble
into valid SQL code. 这里的问题是您的查询将转换为SQL
并在数据库上运行,并且Entity Framework不知道如何将Convert.ToDouble
转换为有效的SQL代码。
So you could cast to double
as below, which will be later converted to SQL CAST AS
statement. 因此,您可以按如下所示将其强制转换为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);
First you can cast the Value
to double then use Max/Min
: 首先,您可以将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;
}
In EF Dbcontext don't support "Convert.ToDouble", you can fix same that: 在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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.