问题描述
||
C#3.0,Nhibernate 2.1.2,Castle ActiveRecord 2.1,WinXP 32
我在使用ActiveRecord和DetachedCriteria过滤元素时遇到问题。
有2个表,一个表包含要过滤的对象(PropertyContainer),另一个表包含为此对象设置的动态属性的值(PropertyValue)。
PropertyContainer
Id int
PropertyValue
Id int
ContainerId int
Value real
我需要选择PropertyContainer对象,其PropertyValue表中的值匹配某些条件(例如,Id = 1且Value> 2的属性)。我想使用DetachedCriteria做到这一点,我试图写这样的东西:
var detachedCriteria = DetachedCriteria.For(typeof(PropertyContainer));
detachedCriteria.SetProjection(
Projections.sqlprojection(@\"select Value from PropertyValue where Id=1\"),new[] { \"ExternalProperty\" },new[] { NHibernateUtil.Double }));
detachedCriteria.Add(Expression.Ge(\"ExternalProperty\",2));
var filteredItems = PropertyContainer.SlicedFindAll(0,100,detachedCriteria);
然后执行此调用,我得到以下错误:
\“无法解析属性:ExternalProperty:PropertyContainer \”
问题是:
这种方法有什么问题?
使用ActiveRecord / NHibernate和DetachedCriteria通过动态属性集进行过滤的正确方法是什么?
解决方法
如果PropertyValue看起来像:
class PropertyValue
{
public virtual int Id { get; set; }
public virtual double Value { get; set; }
}
你可以做:
DetachedCriteria.For<PropertyContainer>()
.CreateAlias(\"PropertyValues\",\"prop\")
.Add(Restrictions.Ge(\"prop.Value\",2))
.Add(Restrictions.Eq(\"prop.Id\",1));