AwkwardCoder
AwkwardCoder

Reputation: 25631

How do I setup a Criteria in nHibernate to query against multiple values

I want to query for a set of results based on the contents of a list, I've managed to do this for a single instance of the class Foo, but I'm unsure how I would do this for a IList<Foo>.

So for a single instance of the class Foo, this works:

        public ICriteria CreateCriteria(Foo foo)
        {
            return session
                .CreateCriteria<Component>()
                .CreateCriteria("Versions")
                .CreateCriteria("PublishedEvents")
                .Add(Restrictions.And(Restrictions.InsensitiveLike("Name", foo.Name, MatchMode.Anywhere),
                                      Restrictions.InsensitiveLike("Type", foo.Type, MatchMode.Anywhere)))
                .SetCacheable(true);
        }

But how do I do this when the method parameter is a list of Foo?

 public ICriteria CreateCriteria(IList<Foo> foos)
    {
        return session
            .CreateCriteria<Component>()
            .CreateCriteria("Versions")
            .CreateCriteria("PublishedEvents")
            .Add(Restrictions.And(Restrictions.InsensitiveLike("Name", foo.Name, MatchMode.Anywhere),
                                  Restrictions.InsensitiveLike("Type", foo.Type, MatchMode.Anywhere)))
            .SetCacheable(true);
    }

Upvotes: 1

Views: 1661

Answers (1)

lomaxx
lomaxx

Reputation: 115763

If you're thinking about what you're trying to do with this query, it doesn't actually make sense to query it in the construct you're using. The only option you really have is to loop through and dynamically create the criteria like so:

 public ICriteria CreateCriteria(IList<Foo> foos)
    {
        var criteria = session
            .CreateCriteria<Component>()
            .CreateCriteria("Versions")
            .CreateCriteria("PublishedEvents")
            .SetCacheable(true);

        foreach(var foo in foos)
        {
            criteria.Add(Restrictions.And(Restrictions.InsensitiveLike("Name", foo.Name, MatchMode.Anywhere),Restrictions.InsensitiveLike("Type", foo.Type, MatchMode.Anywhere)));
        }
        return criteria;
    }

Upvotes: 1

Related Questions