I have a method that returns data by viewing models from multiple tables. The problem occurs when I try to select a column while data is not exiting. Heres my code
public async Task<List<CustomerViewModel>> GetCustomers()
{
return await _context.Customers.Select(x => new CustomerViewModel
{
Id = x.Id,
Name = x.Name,
Phone = x.Phone,
Address = x.Address,
Payment = x.Payment,
Due = x.Due,
Received = x.Received,
DateOfReg = x.DateOfReg,
Quantity = _context.BSells.Where(_ => _.CustomerId == x.Id).Select(_=>_.Quantity).Sum(),
Unitcost = _context.BSells.Where(_ => _.CustomerId == x.Id).FirstOrDefault().UnitPrice
}).ToListAsync();
}
The problem occurs on lines 14, and 15 because the BSell table doesn't have data of the particular customer. Now, what should I do now?
I may not be able to express the problem clearly. Sorry for that.
CodePudding user response:
Alright I've solved the issue by changing code little bit
public async Task<List<CustomerViewModel>> GetCustomers()
{
return await _context.Customers.Select(x => new CustomerViewModel
{
Id = x.Id,
Name = x.Name,
Phone = x.Phone,
Address = x.Address,
Payment = x.Payment,
Due = x.Due,
Received = x.Received,
DateOfReg = x.DateOfReg,
Quantity = _context.BSells.Where(_ => _.CustomerId == x.Id).Select(_=>_.Quantity).Sum(),
Unitcost = _context.BSells.Where(_ => _.CustomerId == x.Id).Select(_ => _.UnitPrice).FirstOrDefault()
}).ToListAsync();
}
I should have selected the column before taking the first value. Is it? I will be really grateful if anyone addresses my mistakes. Thank you.