如何在Castle ActiveRecord中为子项添加where子句

时间:2012-01-31 07:43:09

标签: nhibernate castle-activerecord

我正在使用Castle ActiveRecord并创建了两个实体,如下所示:

    [ActiveRecord("Teams")]
public class Team : ActiveRecordLinqBase<Team>
{
    public Team()
    {
        Members = new List<Member>();
    }

    [PrimaryKey]
    public int Id { get; set; }

    [Property("TeamName")]
    public string Name { get; set; }

    [Property]
    public string Description { get; set; }

    [HasMany(Inverse = true,
             Lazy = true,
             Cascade = ManyRelationCascadeEnum.AllDeleteOrphan)]
    public virtual IList<Member> Members { get; set; }
}

[ActiveRecord("Members")]
public class Member : ActiveRecordLinqBase<Member>
{
    [PrimaryKey]
    public int Id { get; set; }

    [Property]
    public string FirstName { get; set; }

    [Property]
    public string Lastname { get; set; }

    [Property]
    public string Address { get; set; }

    [BelongsTo("TeamId")]
    public Team Team { get; set; }
}   

我使用ICriterion过滤了团队数据

IList<ICriterion> where = new List<ICriterion>();
where.Add(Expression.Eq("Name", "name1"));
ICriterion[] criteria = where.ToArray();

var teams = Team.FindAll(criteria);

到目前为止它运行良好,但我想在Members表上添加另一个过滤器。结果查询就像这样

select *
  from Teams t join Member m on t.Id = m.TeamId
 where t.Name = 'name1'
   and m.Address = 'address'

如何使用ICriterion完成此操作? 我的意思是如何为Team.Members属性添加标准。 不使用LINQ。 (我知道这可以使用linq轻松完成)

1 个答案:

答案 0 :(得分:2)

对于加入,您可以使用 DetachedCriteria

 DetachedCriteria criteriaTeam = DetachedCriteria.For<Team>();
 DetachedCriteria criteriaMember = criteriaTeam .CreateCriteria("Members");
 criteriaTeam .Add(Expression.Eq("Name", "name1"));
 criteriaMember.Add(Expression.Eq("Address", "address"));
 ICriteria executableCriteria = criteriaTeam .GetExecutableCriteria(session);
 executableCriteria.List<Team>();

这将仅返回Team.To返回Team和Members中的一次获取,您可以使用NHibernate结果转换器Projections in NHibernate