Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

c# - Query by discriminator in NHibernate

I did some searching on this and didn't turn up anything. Is it possible to create a Hibernate query to return a set of objects based on a discriminator?

I have an AbstractUser class which is extended by the concrete classes UserTypeA and UserTypeB. I'm using the table-per-hierarchy model to map my classes in NHibernate, so UserTypeA and UserTypeB are both stored in the same table with different discriminator values. Here is my discriminator mapping property:

<discriminator column="Type" type="string"/>

I have a column in my table that contains the name of the user type. I'm wondering if it's possible to run a NHibernate query using this.

I tried this:

public IList<DomainBase> FindByType(string typeName, Type type)
{
    string query = "from " + type.Name + " k where k.Type = " + typeName;
    return Session.CreateQuery(query).List<DomainBase>();
}

But since Type is not actually a property of the class, just a column in the table, this obviously doesn't work. It would seem redundant to have both a property for this purpose and a discriminator, unless there's a way to use a property as a discriminator?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Actually, this is well documented at http://www.nhibernate.info/doc/nh/en/index.html#queryhql-where:

Likewise, the special property class accesses the discriminator value of an instance in the case of polymorphic persistence. A .Net class name embedded in the where clause will be translated to its discriminator value.

 from Eg.Cat cat where cat.class = Eg.DomesticCat

You can also pass a System.Type instance as a parameter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...