问题
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