Getting data from DB from DB through Navigation Properties giving InvalidOperationException

Viewed 38

i am trying to get data from 3 different tables. I want to calculate total purchasing and sales of each store. Currently my Order table have 0 records for some stores. i am getting this error .`

System.InvalidOperationException: 'Nullable object must have a value.'

`

 var stats = context.Stores.Select(s => new StoreStats()
        {
            //StoreID = s.store_id,
            //StoreName = s.StoreName + s.Ref_No,
            //RefNo = s.Ref_No,
            //MonthPurchasing = s.Purchasing != null ? s.Purchasing.Where(x => (x.Date - DateTime.Now).TotalDays <= 30).Sum(x => x.Amount) : 0,
            //MonthPurchasingCount = s.Purchasing != null ? s.Purchasing.Where(x => (x.Date - DateTime.Now).TotalDays <= 30).Count() : 0,
            //AverageMonthlyPurchasing = s.Purchasing != null ? s.Purchasing.Where(x => (x.Date - DateTime.Now).TotalDays <= 30).Count() / 30 : 0,
            //MonthSales = s.Order != null ? s.Order.Where(x => (x.Date - DateTime.Now).TotalDays <= 30).Sum(x => x.Amount) : 0,
            //MonthSalesCount = s.Purchasing != null ? s.Purchasing.Where(x => (x.Date - DateTime.Now).TotalDays <= 30).Count() : 0,
            //AverageMonthlySale = s.Order != null ? s.Order.Where(x => (x.Date - DateTime.Now).TotalDays <= 30).Count() / 30 : 0,
            //MonthlyProfit = (s.Purchasing != null ? s.Purchasing.Where(x => (x.Date - DateTime.Now).TotalDays <= 30).Sum(x => x.Amount) : 0) - (s.Order != null ? s.Order.Where(x => (x.Date - DateTime.Now).TotalDays <= 30).Sum(x => x.Amount) : 0),
            TotalPurchasing = s.Purchasing != null ? s.Purchasing.Sum(x => x.Amount) : 0,
            TotalSales = s.Order != null ? s.Order.Sum(x => x.Amount) : 0,
            TotalProfit = s.Purchasing != null ? s.Purchasing.Sum(x => x.Amount) - s.Order.Sum(x => x.Amount) : 0,
            //CompletedOrders = s.Order != null ? s.Order.Where(x => x.status == Model.Order.Status.Completed).Count() : 0,
            //PendingOrders = s.Order != null ? s.Order.Where(x => x.status == Model.Order.Status.Pending).Count() : 0,
            //TotalEmployees = s.Employees != null ? userManager.Users.Where(x => x.store_id != null && x.store_id == s.store_id).Count() : 0,
            //TotalBrands = s.Stock != null ? s.Stock.Where(x => x.store_id == s.store_id).Count() : 0,
        }).ToList();
        d.Stores = stats;

Edit: After Hard Debugging it is found that the line which is non-commented throwing this exception

0 Answers
Related