Ray
Ray

Reputation: 4108

How to add where clause for child items in Castle ActiveRecord

I am using Castle ActiveRecord and created two entities as follow :

    [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; }
}   

And I used ICriterion to have filtered Team data

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

var teams = Team.FindAll(criteria);

So far it works well, but I want to add another filter on Members table. The result query would be like this

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

How to get this done using ICriterion? I mean how to add criterion for Team.Members property. Not using LINQ. (I know this could be done using linq easily)

Upvotes: 0

Views: 721

Answers (1)

Anand
Anand

Reputation: 757

For join you can use 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>();

This will return only Team.To return both Team and Members in a single fetch you can use NHibernate result transformer Projections in NHibernate

Upvotes: 2

Related Questions