I'm having an issue performing a DTO projection with Entity Framework Core 2.2 whereby one class has a property that references another property from a parent class. When I attempt the projection a NullReferenceException
is thrown because the parent object is null
.
Here is a contrived example of what I'm trying to achieve:
public class Vendor
{
public ICollection<Item> Items { get; set; }
public decimal Tax { get; set; }
}
public class Item
{
public Vendor Vendor { get; set; }
public string Name { get; set; }
public decimal ItemPrice { get; set; }
public decimal TotalPrice => ItemPrice * (1 + Vendor.Tax);
}
public class ItemDto
{
public string Name { get; set; }
public decimal TotalPrice { get; set; }
}
private Task<IEnumerable<ItemDto>> Projection()
{
var results = await _context.Item
.Select(t => new ItemDto()
{
Name = t.Name,
TotalPrice = t.TotalPrice
})
.ToListAsync();
return results;
}
I am able to get this to work by either:
- Grabbing the results of the query first and then performing the projection, but this ends up pulling unnecessary data from the database
- Specifying
TotalPrice = t.ItemPrice * (1 + t.Vendor.Tax)
within the projection, but this is redefining the logic, so isn't ideal
I've also tried including Vendor
in the query, but that doesn't help either. Any ideas on how to solve this would be greatly appreciated!