Shawn
Shawn

Reputation: 1891

Entity Framework Code First with Repository Pattern and lazy loading?

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.

Upvotes: 1

Views: 897

Answers (1)

Be.St.
Be.St.

Reputation: 4181

First of all I suggest you use the session-per-request pattern to handle DbContext.

In Application_BeginRequest method instantiate the DbContext and allow accessing it from your controllers.

In Application_EndRequest dispose/close your DbContext.

Then I think that "requesting a particular person only needs the sales for a given day" is a business rule you must put in a service.

So add a service like EmployeeService to manage your Employee class. Add a method like

Employee GetByDate(DateTime salesDay)

where you load Employee and Sales data for that given date.

You have to inject DbContext also in the EmployeeService.

Upvotes: 1

Related Questions