NHibernate- QueryOver using base classes?

大兔子大兔子 提交于 2020-01-25 01:23:05

问题


Right now I'm using the Criteria API and loving it, but it would be even better if I could make the switch to the QueryOver API. However, my setup is a little strange. In order to partition data into tables, I have one base abstract class:

Listing

and a number of classes which inherit from that:

Listing_UK
Listing_US
etc.

With the criteria API, I can do something like:

Type t = typeof(Listing_UK);
if (condition) t = typeof(Listing_US);
DbSession.CreateCriteria(t)
            .Add(Restriction.Eq("field",value)
            .List<Listing>());

Basically, using the same query on different classes. It seems like the strongly-typed nature of QueryOver prevents me from doing this- the basic problem being that:

DBSession.QueryOver<Listing_UK>()

doesn't cast to

DBSession.QueryOver<Listing>

While I understand why, I'm wondering if anyone has any trick I could use to create a generic QueryOver that will still target the right table?


回答1:


You might find you could use the following overload:

DbSession.CreateCriteria(myDynamicallyDeterminedType)
    .Add(Restrictions.On<Listing>(l => l.field == value))
    .List<Listing>();



回答2:


Technically this should be allowable under certain circumstances. Namely the use of covariance in c#4 and some reflection. I believe that all the changes that would be needed would be to make the IQueryOver interfaces covariant.

subType = typeof(ParentClass).Assembly.GetType(subTypeFullName);

var mi = typeof(QueryOver).GetMethod("Of", new Type[]{});
var gmi = mi.MakeGenericMethod(subType);
var qo = (QueryOver<ParentClass, ParentClass>)gmi.Invoke(null, null);
var queryOver = qo.GetExecutableQueryOver(session);

// your comment restrictions/projections here.

I've wrestled with this idea and as long as we can build against .Net 4 it should work pretty easily.



来源:https://stackoverflow.com/questions/4829303/nhibernate-queryover-using-base-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!