views:

21

answers:

2

I need to define these two Properties to one of my linqclasses (Employee).. because I need to keep track of the health progress of Employees... Each employee takes monthly PhysicalExams so I defined these properties

    public decimal? Initial_Mass_Index
            {
                get
                {
                    return this.PhysicalExams.OrderBy(p => p.Date).First().MassIndex ?? 0;
                }
            }
   public decimal? Current_Mass_Index
            {
                get
                {
                    return this.PhysicalExams.OrderByDescending(p => p.Date).First().MassIndex ?? 0;
                }
        }

My question is.. my app is using the Repository Pattern and I have read that it is not proper practice to have Data Access inside the Model Classes...

What do you guys reccomend?? please help thanks in advance

A: 

you can Create a Class like ExtendedEmployee which inherits your Employee model

public class ExtendedEmployee : Employee
{
    public decimal? Initial_Mass_Index
    {
        get
        {
            return this.PhysicalExams.OrderBy(p => p.Date).First().MassIndex ?? 0;
        }
    }
    public decimal? Current_Mass_Index
    {
        get
        {
            return this.PhysicalExams.OrderByDescending(p => p.Date).First().MassIndex ?? 0;             
        }
    }
}

and use this ExtendedEmployee as your Model.

rob waminal
A: 

Couple observations: There's no need to make the decimal nullable, since you're nulll coalescing it anyway. Also, you don't need to create an ExtendedEmployee, since you can just add to the partial class.

I would probably lean towards implementing an IMassIndexRepository

public interface IMassIndexRepository
{
   public decimal GetInitialMassIndex(Employee e);
   public decimal GetCurrentMassIndex(Employee e);
}

Then if you want to have this as part of your model, you can add an extension method or reference the repository in the model. I would lean toward the latter:

public partial class Employee
{
    public decimal? Initial_Mass_Index
    {
        get
        {
            return GetMassIndexRepository().GetInitialMassIndex(this);
        }
    }

    public decimal? Current_Mass_Index
    {
        get
        {
            return GetMassIndexRepository().GetCurrentMassIndex(this);
        }
    }
}

You'll have to implement GetMassIndexRepository (probably using some DI container). Once you have a MassIndexRepository, you can implement caching at that level, and doing the 'data access' won't be as impacting on performance as a straight Linq property call.

Shlomo