繁体   English   中英

Entity Framework中按字符串的MIN和MAX值

[英]MIN and MAX value by string in Entity Framework

我有数据库表。 它的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; }

如您所见,值是字符串类型。 我正在尝试通过此字段获取最小值和最大值(某些值表示为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)',并且该方法无法转换为商店表达式。

那么,如何搜索类似于小数的字符串值?

这里的问题是您的查询将转换为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);

首先,您可以将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;
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM