Linq to sql 帮助向LinqToSql类添加属性

Linq to sql 帮助向LinqToSql类添加属性,linq-to-sql,asp.net-mvc-2,Linq To Sql,Asp.net Mvc 2,我需要为我的一个LinqClass(Employee)定义这两个属性。。因为我需要跟踪员工的健康进展。。。每个员工每月进行一次体检,所以我定义了这些属性 public decimal? Initial_Mass_Index { get { return this.PhysicalExams.OrderBy(p => p.Date).First().Mass

我需要为我的一个LinqClass(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;
                }
        }
我的问题是。。我的应用程序正在使用Repository模式,我已经了解到在模型类中进行数据访问是不合适的做法

你们有什么建议?? 请帮忙
提前感谢

您可以创建一个类似ExtendedEmployee的类,该类继承您的Employee模型

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;             
        }
    }
}

并使用此扩展员工作为您的模型。

结合观察:没有必要使十进制为空,因为您正在合并它。此外,您不需要创建ExtendedEmployee,因为您只需将其添加到分部类中即可

我可能倾向于实现IMassIndexRepository

public interface IMassIndexRepository
{
   public decimal GetInitialMassIndex(Employee e);
   public decimal GetCurrentMassIndex(Employee e);
}
然后,如果希望将其作为模型的一部分,可以在模型中添加扩展方法或引用存储库。我倾向于后者:

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

    public decimal? Current_Mass_Index
    {
        get
        {
            return GetMassIndexRepository().GetCurrentMassIndex(this);
        }
    }
}
您必须实现GetMassIndexRepository(可能使用一些DI容器)。一旦有了MassIndexRepository,就可以在该级别实现缓存,并且执行“数据访问”不会像直接调用Linq属性那样影响性能