Consider the following simple example:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
... other employee properties ...
public virtual ICollection<Sale> Sales { get; set; }
}
public class Sale
{
public int Id { get; set; }
public int EmployeeId { get; set; }
public DateTime DateSold { get; set; }
... other sale properties ...
public virtual Employee Employee { get; set; }
}
public class SampleContext: DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Sale> Sales { get; set; }
}
I create a repository that uses the above entity framework context to return employees by id:
public interface IRepository
{
Employee EmployeeById(int id);
}
My question is in regards to populating and returning employee sales. In the vast majority of use cases, the code requesting a particular person only needs the sales for a given day. How should I handle that? Do I extend the Employee class to some EmployeeWithDailySales object?
I can't use lazy loading in the calling function as the DbContext reference does not exist once I return from the repository class. Does that mean I am doing something incorrect to begin with? Is my idea of the repository itself flawed?
I could preload the employee's sales when I initially populate the Employee object but that would likely result in many unneeded records in most situations.
Any advice is greatly appreciated. I am still trying to get a clear understanding of how to use these patterns and frameworks correctly.