无法使用NLinq创建实体规范

时间:2010-09-01 03:32:15

标签: nhibernate fluent-nhibernate specification-pattern

我正在使用规范模式,并且有一个工作实现(取自WhoCanHelpMe Codeplex项目),用于通过NLinq获取数据,通用存储库以及所有这些优点。

根方法是:

public IList<Case> GetCasesByUsername(string username)
{
    CaseByUserNameSpecification spc = new CaseByUserNameSpecification(username);
    return this.caseRepository.FindAll(spc).ToList();
}

FindAll()方法执行以下操作:

public IQueryable<T> FindAll(ILinqSpecification<T, T> specification)
{
    return specification.SatisfyingElementsFrom(this.Session.Linq<T>());
}

并且,SatisfyingElementsFrom()执行此操作:

public virtual IQueryable<TResult> SatisfyingElementsFrom(IQueryable<T> candidates)
{
    if (this.MatchingCriteria != null)
    {
        return candidates.Where(this.MatchingCriteria).ToList().ConvertAll(this.ResultMap).AsQueryable();
    }

    return candidates.ToList().ConvertAll(this.ResultMap).AsQueryable();
}

因此,对于通过Case的CaseNb属性查询案例,它非常简单。像下面那样的规范适用于我并获得我想要的案例。

public class CaseByCaseNbSpecification : QuerySpecification<User>
{
    private string caseNb;

    public CaseByCaseNbSpecification(string caseNb)
    {
        this.caseNb = caseNb;
    }

    public string UserName
    {
        get { return this.caseNb; }
    }

    public override Expression<Func<Case, bool>> MatchingCriteria
    {
        get { return u => u.CaseNb.Equals(this.caseNb, StringComparison.CurrentCultureIgnoreCase); }
    }

}

但是,在跨越多个实体时,我无法理解如何执行此操作。我想要的是一个规范,允许我通过UserName获取案例。基本上,在数据库中,有三个表,这些表已被带入实体。这是实体:

以下是Case类:

public class Case : Entity
{
    private ICollection<CaseUser> caseUsers = new HashSet<CaseUser>();

    public virtual Patient Patient { get; set; }
    public virtual string CaseNb { get; set; }
    ...
    public virtual IEnumerable<CaseUser> CaseUsers { get { return caseUsers; } }
}

这是CaseUser:

public class CaseUser : Entity
{
    public virtual Case Case { get; set; }
    public virtual User User { get; set; }
    ...
}

而且,用户:

public class User : Entity
{
    private ICollection<CaseUser> caseUsers = new HashSet<CaseUser>();

    public virtual Account Account { get; set; }
    public virtual string UserName { get; set; }
    ...
    public virtual IEnumerable<CaseUser> CaseUsers { get { return caseUsers; } }
}

如何编写Expression以通过关联表获取数据?

1 个答案:

答案 0 :(得分:0)

我相信你的规范实现应该是这样的:

public class CaseByUsernameSpecification : QuerySpecification<Case> 
{ 
    private string userName; 

    public CaseByUsernameSpecification(string userName) 
    { 
        this.userName = userName; 
    } 

    public string UserName 
    { 
        get { return this.userName; } 
    } 

   public override Expression<Func<Case, bool>> MatchingCriteria 
    { 
        get { return c => c.CaseUsers.Any(cu => cu.User.Username == this.userName); } 
    } 

}