Linq Select 列如果数据存在

Linq Select column if data exits

我有一种方法可以通过查看来自多个 table 的模型来 returns 数据。当我尝试 select 列而数据不存在时,就会出现问题。这是我的代码

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 table 没有特定客户的数据。现在,我该怎么办?

我可能没有把问题表达清楚。对不起。

好的,我通过稍微更改代码解决了这个问题

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();
}

我应该在取第一个值之前选择列。是吗?如果有人解决我的错误,我将非常感激。 谢谢。