Entity Framework中按字符串的MIN和MAX值 [英] MIN and MAX value by string in Entity Framework

查看:60
本文介绍了Entity Framework中按字符串的MIN和MAX值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数据库表.它的ORM是:

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

您可以看到value是一个字符串类型.我正在尝试通过此字段获取最小值和最大值(某些值表示为double).所以这是我的方法:

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

但是我得到了例外:

LINQ to Entities无法识别方法'Double ToDouble(System.String)',并且该方法无法转换为商店表达式.

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?

推荐答案

首先,您可以将 Value 转换为两倍,然后使用 Max/Min :

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

这篇关于Entity Framework中按字符串的MIN和MAX值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆