我有一個方法可以通過查看多個表中的模型來回傳資料。當我在資料未退出時嘗試選擇列時會出現問題。這是我的代碼
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();
}
問題出現在第 14 行和第 15 行,因為 BSell 表沒有特定客戶的資料。現在,我現在該怎么辦?
我可能無法清楚地表達問題。對此感到抱歉。
uj5u.com熱心網友回復:
好吧,我通過稍微更改代碼解決了這個問題
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();
}
我應該在取第一個值之前選擇該列。是嗎?如果有人解決我的錯誤,我將不勝感激。謝謝你。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/483893.html
