【问题标题】:Filtering objects using ActiveRecord,NHibernate, DetachedCriteria使用 ActiveRecord、NHibernate、DetachedCriteria 过滤对象
【发布时间】:2011-06-14 11:41:27
【问题描述】:

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

我需要从 PropertyValue 表中选择符合某些条件的值的 PropertyContainer 对象(例如,Id = 1 且值 > 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);

然后执行此调用我收到以下错误: “无法解析属性:外部属性:PropertyContainer”

问题是:

  1. 这种方法有什么问题?
  2. 使用 ActiveRecord/NHibernate 和 DetachedCriteria 通过动态属性集进行过滤的正确方法是什么?

【问题讨论】:

    标签: c# nhibernate activerecord filter detachedcriteria


    【解决方案1】:

    如果 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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2018-12-14
      • 1970-01-01
      相关资源
      最近更新 更多