MIN and MAX value by string in Entity Framework

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-29 06:05:53

问题


I have database table. The ORM for it is:

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). 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.

So how can I search for a string value like a decimal?


回答1:


First you can cast the Value to double then use 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:


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.

So you could cast to double as below, which will be later converted to SQL CAST AS statement.

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);



回答3:


In EF Dbcontext don't support "Convert.ToDouble", you can fix same that:

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;
        }


来源:https://stackoverflow.com/questions/37586926/min-and-max-value-by-string-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!