如何使用linq实体获取一个类型为float的列

时间:2015-02-05 19:07:58

标签: c# linq entity-framework

我是EF和Linq的新成员。我想得到一个名为“Value”的列,其类型为float。我的代码如下所示。因此,当我调用下面的方法时,我在行双倍价格上得到错误.....输入字符串的格式不正确。有没有办法将列“Value”作为双精度返回?或者如何将其转换为Double。提前致谢。

 public double calculate_price(int code, int quatity)
    {
        using( var context = new DryTypeEntities())
        {
            var result = context.Table_Products.Where(p => p.Code == 3).Select(p => p.Value) ;            
            string something = result.ToString();
            double price = Convert.ToDouble(something);
            double quant = Convert.ToDouble(quatity);
            double total = price * quant; 
            return total ;                             
        }

    }

3 个答案:

答案 0 :(得分:1)

选择不会返回您期望的值。

更改为。

var result = context.Table_Products.Where(p => p.Code == 3).Select(p => p.Value).FirstOrDefault() ; 

您可能应该检查结果是否为空。

答案 1 :(得分:1)

此错误表示A)something是字符串而不是双精度,而B)something的内容格式不正确,无法转换为double。

你没有展示contains的内容,但这就是你应该关注的内容。

所以猜测你想要什么,你可能想做这样的事情:

using( var context = new DryTypeEntities())
{
    var result = context.Table_Products.Where(p => p.Code == 3).Select(p => p.Value) ;            
    foreach (var r in result)
    {
        double price = Convert.ToDouble(r);
        // There is no quatity returned by your query
    }
}

注1:您的查询专门选择Value,因此结果仅包含“值”列。查询返回的值不是quatity

注意2:您的查询返回一个集合(一组零个或多个元素),而不仅仅是一个元素。我认为这是你真正想要的:

using( var context = new DryTypeEntities())
{
    var result = context.Table_Products.FirstOrDefault(p => p.Code == 3);            
    return result.Value * result.quantity;
}

答案 2 :(得分:0)

这将返回Value的集合:

 var result = context.Table_Products
                     .Where(p => p.Code == 3)
                     .Select(p => p.Value);

然后,这会将您的集合的字符串表示形式存储在something中(而非您的意图):

string something = result.ToString();
    // System.Collections.Generic.List`1[System.Int32] or something equally unhelpful

无法转换为价格,因此失败:

double price = Convert.ToDouble(something);   // uh, no.

相反,一个选项是获取第一条记录:

 var result = context.Table_Products
                     .Where(p => p.Code == 3)
                     .Select(p => p.Value);
                     .First();

或者,如果确保只有一个匹配“代码”3:

 var result = context.Table_Products
                     .Where(p => p.Code == 3)
                     .Select(p => p.Value);
                     .Single();

现在result包含一个Value,您可以使用该单个值。

还有其他的东西需要考虑(即,如果没有匹配的记录,如果有多个记录要迭代,等等。),但这应该让你再去。

最后一点 - consider using decimal for money values代替double