编译表达式和规范模式(NHibernate)

时间:2014-12-11 15:36:04

标签: nhibernate expression-trees linq-expressions linq.compiledquery

我正在使用一个IRepository来访问NHibernate,其中存储库公开了一个Find方法,该方法接受规范但是当我真正想要传递ID时,却无法在不传递具体对象的情况下找到处理规范的方法。 .. 我的存储库是这样实现的,NHiberate在幕后......

IEnumerable<T> FindAll(ISpecification spec)

我正在实现的抽象类看起来像这样:

/// <summary>
/// Defines an abstract specification with an expression, where the
/// expression is compiled when IsSatisfiedBy is invoked.
/// </summary>
/// <typeparam name="T">The type of object this specification supports.</typeparam>
public abstract class SpecificationWithExpressionBase<T> : ISpecificationWithExpression<T>
{
    /// <summary>
    /// Stores the compiled expression.
    /// </summary>
    private Func<T, bool> _compiledExpression;

    /// <summary>
    /// Gets a compiled expression.
    /// </summary>
    private Func<T, bool> CompiledExpression
    {
        get { return _compiledExpression ?? (_compiledExpression = SpecExpression.Compile()); }
    }

    /// <summary>
    /// The expression of the specification.
    /// </summary>
    public abstract Expression<Func<T, bool>> SpecExpression { get; }

    /// <summary>
    /// Checks whether the object is satisfied by this specification.
    /// </summary>
    /// <param name="obj">The object to check.</param>
    /// <returns>True if this object has been satisfied. False otherwise.</returns>
    public bool IsSatisfiedBy(T obj)
    {
        return CompiledExpression(obj);
    }
}

如果我有两个班级......

class Member 
{
    public int Id { get; set; }
    public Template Template { get; set; }
}

class Template
{
    public int Id { get; set; }
}

...我创建了两个规范来确定成员是否绑定到给定模板,如下所示:

class IsBoundToTemplateFailing : SpecificationWithExpressionBase<Member>
{
     int _templateId;

     public IsBoundToTemplate(int templateId) 
     {
         _templateId = templateId;
     }

     public override Expression<Func<Member, bool>> SpecExpression 
     { 
         get { return s => s.Template.Id == _templateId; }
     }
}

class IsBoundToTemplateSucceeding : SpecificationWithExpressionBase<Member>
{
     Template _template;

     public IsBoundToTemplate(Template template) 
     {
         _template = template;
     }

     public override Expression<Func<Member, bool>> SpecExpression 
     { 
         get { return s => s.Template == template; }
     }
}

当将规范传递给存储库(NHibernate实现)时,第一个失败而另一个失败可能是因为编译了expresson。 NHibernate引发了一个例外cannot resolve property "Id" of the class "Template"

是否可以构造规范,以便可以传递标识符而不是实例?

0 个答案:

没有答案