I am currently working with ASP.NET Core 1.0 using Entity Framework Core. I have some complicated calculations with data from a database, and I'm not sure how to build the right architecture using Dependency Injection without creating an anemic domain model ( http://www.martinfowler.com/bliki/AnemicDomainModel.html )
(simplified) Example:
I have the following objects:
public class Project { public int Id {get;set;} public string Name {get;set;} } public class TimeEntry { public int Id {get;set;} public DateTime Date {get;set;} public int DurationMinutes {get;set;} public int ProjectId {get;set;} public Project Project {get;set;} } public class Employee { public int Id {get;set;} public string Name {get;set;} public List<TimeEntry> TimeEntries {get;set;} }
I want to do some complicated calculations to calculate the monthly timeshare. Since I cannot access the database in the Employee entity, I compute the TimeSheet in the EmployeeService .
public class EmployeeService { private DbContext _db; public EmployeeService(DbContext db) { _db = db; } public List<CalculatedMonth> GetMonthlyTimeSheet(int employeeId) { var employee = _db.Employee.Include(x=>x.TimeEntry).ThenInclude(x=>x.Project).Single(); var result = new List<CalculatedMonth>();
If I want to get a TimeSheet, I need to enter an EmployeeService and call GetMonthlyTimeSheet .
So - I get many GetThis () and GetThat () methods inside my service, although these methods fit perfectly in the Employee class.
What I want to achieve is something like:
public class Employee { public int Id {get;set;} public string Name {get;set;} public List<TimeEntry> TimeEntries {get;set;} public List<CalculatedMonth> GetMonthlyTimeSheet() { var result = new List<CalculatedMonth>();
... but for this I need to make sure that the TimeEntries list is populated from the database (EF Core does not support lazy loading). I do not want. Include (x => y) everything in every request, because sometimes I just need an employee name without time, and this will affect application performance.
Can someone tell me how to do this correctly?
Edit: One of the possibilities (from the comments of the first answer):
public class Employee { public int Id {get;set;} public string Name {get;set;} public List<TimeEntry> TimeEntries {get;set;} public List<CalculatedMonth> GetMonthlyTimeSheet() { if (TimeEntries == null) throw new PleaseIncludePropertyException(nameof(TimeEntries)); var result = new List<CalculatedMonth>();