I have a simple data model and I am using EF4.1 code first (but the problem seems to be relevant to any EF4 approach) as an ORM to store and retrieve data.
The model looks somewhat like:
public class Customer
{
public int CustomerId { get; set; }
public string Name { get; set; }
public virtual List<Product> Products { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public virtual ICollection<Event> Events { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
}
public class Event
{
public int EventId { get; set; }
public string Name { get; set; }
public virtual List<Product> Products { get; set; }
}
So the entity relationships are like:
Customer —– Product —– Event
An event affects N Products (eg. a raise in price or a deal on a product)
Each Customer has N Products belonging to him.
Now for every Event in the database I would like to get a set (note non duplicate entries) of Customers affected by this Event. A customer is affected by the event if he has at least one product affected by the event.
The naive implementation would be:
foreach (var ev in context.Events)
{
foreach(var product in ev.Products)
{
//Check for customers with this product and add them to the list of affected customers
}
}
But this seems like an anti-pattern. The question is:
How to write a query to solve this problem in a more effective manner? (maybe linq, but even native SQL would help)?
You might be looking for a query like this: