2

I have a issue in using subquery with queryover.

This is what I have

      var address = QueryOver.Of<Address>()
            .Where(x => x.City.IsLike("%" + city + "%")).Select(x => x.Person.Id);

        var result = Session.QueryOver<Person>()
            .Where(x => x.Type.IsLike(type + "%"))
            .And(x => x.Name.IsLike("%" + name + "%"))
            .WithSubquery.WhereExists(address);

I have a table for Person and a person has multiple addreses.

So Person id, name, type

and Address will have PersonId and city etc.

So want to search a person by name and type as well as City which is in Address table

4

1 回答 1

6

尝试这样的事情:

Address address = null;
Person person = null;
var addressSubQuery = QueryOver.Of<Address>(() => address)
    .Where(Restrictions.EqProperty(Projections.Property(() => address.Person.Id), Projections.Property(() => person.Id)))
    .Where(() => address.City.IsLike("%" + city + "%"));

    var result = Session.QueryOver<Person>(() => person)
        .Where(x => x.Type.IsLike(type + "%"))
        .And(x => x.Name.IsLike("%" + name + "%"))
        .WithSubquery.WhereExists(addressSubQuery);

您需要使用 QueryOver 的别名版本。通过这种方式,您可以从其他查询中引用 Person 元素,这些查询最终将链接到您的主查询中。

这与执行以下操作相同

Select * from Person
Where 
    Type like '%foo%'
    and Name like '%bar%'
    and exists ( select Id from Address 
                 where 
                      Address.PersonId = Person.Id
                      and Address.City like '%bar%' )
于 2011-06-17T13:41:41.557 回答