vgru
vgru

Reputation: 51224

Creating a "where in" HQL query

I am having trouble writing a HQL query which uses a "where in" clause.

Simplified classes look like this:

class Parent
{
    public virtual Int64 Id { get; private set; }
    public virtual string Name { get; private set; }
}

class Child
{
    public virtual Int64 Id { get; private set; }
    public virtual string Name { get; private set; }
    public virtual Parent Parent { get; private set; }
}

With mapping defined like this:

class ParentMap : ClassMap<Parent>
{
    Id(x => x.Id);
    Map(x => x.Name);
}

class ChildMap : ClassMap<Child>
{
    Id(x => x.Id);
    Map(x => x.Name);
    References(x => x.Parent);
}

I wanted to get Child instances which belong to certain Parent items, so I wrote the following code:

// get children for several parents (a flattened list)
IEnumerable<Parent> parents = GetParents();

// use hql
IQuery q = Session.CreateQuery("from Child as c where c.Parent in (:parents)");
q.SetParameter("parents", parents);

but the problem is, I am getting the following exception at q.SetParameter:

Test method Can_get_children_for_many_parents threw exception:
  NHibernate.PropertyAccessException:
  Exception occurred getter of Some.Namespace.Parent.Id 
  ---> System.Reflection.TargetException: Object does not match target type.

[Edit]

I tried using q.SetParameter("parents", parents.Select(p => p.Id);, but I get the same exception.

Upvotes: 3

Views: 1882

Answers (1)

Iridio
Iridio

Reputation: 9271

Try with something like this:

q.SetParameterList("parents", parents.ToList());

Upvotes: 6

Related Questions