【问题标题】:IQueryable<decimal> to decimalIQueryable<decimal> 转十进制
【发布时间】:2017-04-11 15:08:10
【问题描述】:

我有一个模型类,其中包含十进制类型的属性 ProductPrice。我无法将 IQueryable 类型存储到属性小数。我什至尝试过 Convert.ToDecimal 但它仍然显示错误。

模型 - 产品

public class Product
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public decimal ProductPrice { get; set; }
    public int ProductQty { get; set; }
}

模型 CartDispay

public class CartDisplay
{
    public int ItemId { get; set; }
    public String ProductName { get; set; }
    public int ProductQty { get; set; }
    public decimal ProductPrice { get; set; }
}

控制器

public ActionResult Index()
    {
        int userId = 3;
        var items = _context.Cart.Join(_context.Items, c => c.CartId, i => i.CartId, (c, i) => new { c, i }).Where(c => c.c.UserId == userId).ToList();
        foreach(var item in items)
        {
            CartDisplay display = new CartDisplay();
            display.ItemId = item.i.ItemId;
            display.ProductName = _context.Product.Where(p => p.ProductId == item.i.ProductId).Select(p => p.ProductName).ToString();
            display.ProductPrice = _context.Product.Where(p => p.ProductId == item.i.ProductId).Select(p => p.ProductPrice); ;
            display.ProductQty = item.i.ProductQty;
            cartView.CartDisplay.Add(display);
        }
        retu

【问题讨论】:

  • 您为什么希望能够将IQueryable&lt;decimal&gt; 存储到decimal 中?一个描述查询,一个描述实际值。也许您想在查询末尾添加.FirstOrDefault(),但这完全取决于您的业务逻辑。
  • FirstOrDefault 而不是 Where..
  • _context.Product.Where(p => p.ProductId == item.i.ProductId).Select(p => p.ProductPrice);这可能会返回多条记录,并且由于您的模型 CartDisplay 只有 ProductPrice (不是集合),您可能会收到此错误。您可以使用 FirstOrDefault() 从返回的集合中给出第一个值。或者你可以改变你的模型结构。

标签: c# asp.net-mvc


【解决方案1】:

IQueryable&lt;T&gt; 定义了T 类型的元素序列,而不是单个项目。它还允许您在不将序列放入内存的情况下执行其他查询,但这在您的问题上下文中并不重要。

不过,您的情况要简单得多:与其查询单个属性,不如通过 ID 查询整个产品,然后获取其各个属性,如下所示:

var prod = _context.Product.SingleOrDefault(p => p.ProductId == item.i.ProductId);
if (prod != null) {
    display.ProductName = prod.ProductName
    display.ProductPrice = prod.ProductPrice;
    display.ProductQty = ...
} else {
    // Product with id of item.i.ProductId does not exist
}

【讨论】:

    猜你喜欢
    • 2018-09-22
    • 2020-11-23
    • 2019-09-24
    • 2018-05-21
    • 2014-04-20
    • 2014-01-07
    • 2012-04-08
    • 1970-01-01
    相关资源
    最近更新 更多