I am trying to achieve something with Linq and Entity Framework. What I am trying to achieve is exactly the same as this question:
LINQ: dot notation equivalent for JOIN
In my case though I want to load a customer and related invoices but only certain invoices, not all of them.
I have tried to implement the given answer in the above link but my invoices come out as null.
public IEnumerable<Customer> GetAllCustomers()
{
List<Customer> customers;
using (var context = new EfContext())
{
customers = context.Customers.Join
(
context.Invoices,
c => c.Id,
i => i.CustomerId, (c, i) => new { c, i }
).Where(z => z.i.Id > 3)
.Select(z => z.c).ToList();
}
return customers;
}
This seems to work, just need to double check it:
public Customer GetCustomer(int id)
{
Customer customer;
using (var context = new EfContext())
{
customer = context.Customers.Where(c => c.Id == id)
.Select(c => new
{
c,
Invoices = c.Invoices.Where(i => i.Id > 0 && i.Lines.Any(li => li.Item == "Bacon"))
.ToList().Select(z => new { z, Lines = z.Lines.Where(l => l.Item == "Bacon")}).ToList()
})
.ToList()
.Select(x => x.c)
.FirstOrDefault();
}
return customer;
}