开发者

HQL Query 2 sub classes with a property by the same name

I have 3 classes like:

public class Animal
{
   ... all sort of data ...
}

public class Cat : Animal
{
   ... more data ...

   public virtual int Size { get; set; }
}

public class Dog : Animal
{
   ... other data ...

   public virtual int Size { get; set; }
}

The classes are mapped using the "table per hierarchy" strategy in the hbm.xml mapping the Cat's Size property is mapped to a CatSize column and the Dog's property to DogSize

The following two queries work as expected:

From Cat o Where o.Size = 1
From Dog o Where o.Size = 1

Now I want to query Animal for all the cats where Size = 1 and all the dogs where size = 1, combining the two queries above I get:

From Animal Where o.Size = 1 Or o.Size = 1

That obviously doesn't do what I want, how can I tell NHibernate the first Size is Cat.Size and the second is Dog.Size (preferably without knowing the column names in the database).

Note: I understand the design is problematic an having two properties with the same name in different subclasses is not the smartest design decision ever ma开发者_Python百科de - but changing it now is even more problematic and I'd like to avoid it (the project should be delivered to the client in a few days and I really don't want to make design changes now).

I'm using NHibernate 2.0.1 (upgrading is not an option, the program does not work with later versions of NHibernate and we don't have time to fix it now).


Try this...

select a from Animal a where a in (select c from Cat c where c.Size = 1) or a in (select d from Dog d where d.Size = 1)


Why didn't you define the Size property on the Animal class ?

You can use a MultiQuery to execute the 2 queries in one roundtrip, and that will give you the results as well. I think that this will be the best solution ...

IMultiQuery q = session.CreateMultiQuery();
q.Add("from Cat where Size = 1");
q.Add("from Dog where Size = 1");

var results = q.List();
var cats = (IList)results[0];
var dogs = (IList)results[1];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜