Using Partial Classes in Entity Framework with Custom Properties
How do I handle a custom property in a situation where I am using partial classes with EF generated classes?
Here's the setting:
TimeSheet is Employee Hours
- TimeSheetID (auto, int, PK)
- EntryDate (DateTime)
- Hours (int)
- EmployeeID (int)
EmployeeHourlyRate table - This stores the current hourly rate of the employee. Historical rates are also stored here.
- RateID (int, PK)
- EffectiveDate (int, PK)
- Rate (double)
This is a one-to-many relationship from TimeSheet to EmployeeHourlyRate. To find the Employee metric, I would choose max effectiveDate less than timeHheet EntryDate.
To make things easier, I made a partial class called TimeSheet and added a new property called "Rate" for this class. What I would like to do is fill this with me from the same request that populates my TimeSheets collection. I just know there is no easy and clean way to handle this.
For example, I could do it like this:
var list = from ts in Context.TimeSheets
....
select new TimeSheet() {
TimeSheetID = ts.TimeSheetID,
EntryDate = ts.EntryDate,
Hours = ts.Hours,
EmployeeID = ts.EmployeeID,
Rate = SomeRate //real code has been omitted
};
This should work in theory, but for some reason EF is complaining at runtime that I'm reusing the entity-generated class (don't know why - it works great if I create my own custom class). However, even if it did work, I still have to maintain a list of fields and keep mapping them from EF to one class, i.e. Maintenance becomes a problem when / if I add new fields to the TimeSheet. It's also silly to rewrite all this information.
So my question is, how do people usually deal with this scenario? Is there a way to do something in the datamodel that can efficiently find out my join rule (about choosing the correct effective date based on my EntryDate) and deal with it?
a source to share
I would like to see your full LINQ query (including the "SomeRate" code) to see exactly what you are trying to achieve, but perhaps something like this might work:
WARNING: air code.
public partial class TimeSheet
{
public double Rate
{
get //Calculate your rate here... e.g.
{
if ((this.Employee == null) || (this.Employee.EmployeeHourlyRates.Count == 0))
//throw an exception
EmployeeHourlyRate maxRate;
foreach (EmployeeHourlyRate rate in this.Employee.EmployeeHourlyRates)
{
if ((rate.EffectiveDate <= this.EntryDate)
&& ((maxRate == null) || (maxRate.EffectiveDate < rate.EffectiveDate)))
{
maxRate = rate;
}
}
if (maxRate == null)
//throw exception
else
return maxRate.Rate;
}
}
}
EDIT: Adding an example of active load to avoid database duplication.
var list = from ts in Context.TimeSheets.Include("Employee.EmployeeHourlyRate")
where blah blah
select ts;
a source to share