An EF Core v7 query:
var results = await _context
.Customers
.Join(
_context.Orders.AsNoTracking(),
customer => customer.Reference,
order => order.Reference,
(customer, order) => new { // I only want properties in this anonymous type
Reference = customer.Reference,
CustomerId = customer.Id,
CustomerName = customer.Name,
CustomerAddress = customer.Address,
OrderId = order.Id,
OrderDate = order.Date,
OrderValue = order.Value,
})
.AsNoTracking()
.ToListAsync();
It generates something like this:
SELECT c."Id", c."Reference", c."Name", c."Address",
o."Id", o."Date", o."Value", o."Reference", o."Discount", o."Operator", o."Store", o."Quantity", o."PaymentType", o."Repeat", o."LastPlaced", o."Warehouse", o."StockCode", o."Supplier"
FROM "Customer" AS c
INNER JOIN "Order" AS o ON c."Reference" = o."Reference"
Notice it includes all properties of the Order
entity, not just the ones I used in the projection.
Approach 2: I also tried this in the join:
// ...
.Join(
_context.Orders.AsNoTracking().Select(x => new { x.Reference, x.Id, x.Date, x.Value }),
// ...
Approach 3: I also tried projecting to this:
// ...
.Join(/*...*/)
.Select(x = new {
Reference,
CustomerId,
CustomerName,
CustomerAddress,
OrderId,
OrderDate,
OrderValue,
})
// ...
But those approaches also didn’t restrict the results.
What is the correct way to do this?