请帮助我解决该错误 The cast to value type 'System.Decimal' failed because the materialized value is null.

Jiale Xue - MSFT 43,046 信誉分 Microsoft 供应商
2024-02-29T06:23:00.3633333+00:00

我有错误:转换为值类型“System.Decimal”失败,因为具体化值为空。

结果类型的泛型参数或查询必须使用可为 null 的类型。

请帮助我解决该错误。

如果值为空,则会发生错误.

public partial class Warehouse
    {
        public int WarehouseId { get; set; }
        public bool Operation { get; set; }
        public DateTime DateOperation { get; set; }
        public int NomenclatureId { get; set; }
        public decimal Quantity { get; set; }
        public string Notes { get; set; }
        public virtual Nomenclature Nomenclatures { get; set; }
    }

using (var db = new ContextTest())
            {

                var creditBy = from row in db.Warehouses
                               group row by row.Nomenclatures.NomenclatureName into byNomenclature
                               select new { Date = byNomenclature.Key, CreditTotal = byNomenclature.Where(o => o.Operation == true).Sum(o => o.Quantity) };

                var expenseBy = from row in db.Warehouses
                                group row by row.Nomenclatures.NomenclatureName into byNomenclature
                                select new { Date = byNomenclature.Key, ExpenseTotal = byNomenclature.Where(o => o.Operation == false).Sum(o => o.Quantity) };

                var q = from o in creditBy
                        join e in expenseBy on o.Date equals e.Date
                        select new
                        {
                            o.Date,
                            o.CreditTotal,
                            e.ExpenseTotal,
                            Total = o.CreditTotal - e.ExpenseTotal
                        };
                grid.DataSource = q.ToList();
            }

Note:此问题总结整理于:Please help me get around the error.

.NET
.NET
基于 .NET 软件框架的 Microsoft 技术。
47 个问题
0 个注释 无注释
{count} 票

接受的答案
  1. Hui Liu-MSFT 47,421 信誉分 Microsoft 供应商
    2024-02-29T07:16:33.2633333+00:00

    你好,问题是 Quantity 属性类型是不可为空的,当源为 null 时,EF 需要能够存储一个可为 null 的值。
    因此,您可以使 Quantity l 属性可为 null 来修复它。

    public partial class Warehouse  
    {  
       public decimal? Quantity { get; set; }  
    }
    
    
    

    如果回复有帮助,请单击“接受答案”并投赞成票。 注意:如果您想接收此线程的相关电子邮件通知,请按照我们文档中的步骤启用电子邮件通知。

    0 个注释 无注释

0 个其他答案

排序依据: 非常有帮助