【问题标题】:MIN and MAX value by string in Entity Framework实体框架中字符串的最小值和最大值
【发布时间】:2016-06-02 08:48:02
【问题描述】:

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

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

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)' 方法,并且此方法无法转换为存储表达式。

那么如何搜索小数这样的字符串值呢?

【问题讨论】:

    标签: c# entity-framework linq


    【解决方案1】:

    这里的问题是您的查询将被翻译成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);
    

    【讨论】:

    • 感谢您的解释!
    【解决方案2】:

    首先你可以将Value 转换为double 然后使用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 功能以及在哪里使用它;-)
    • 成功了吗?你试过了吗?因为当我在写完答案后尝试它时,我意识到它不适合你的情况。如果它有效,我可能错过了一些东西。
    • 好的,那我很高兴!
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多