How to express this LINQ query using the NHibernate ICriteria API?

My current project uses NHibernate 3.0b1 and the API NHibernate.Linq.Query<T>(). I am fluent in LINQ, but I have absolutely no experience with HQL or the ICriteria API. One of my queries is not supported by the IQueryable API, so I assume I need to use one of the previous APIs, but I don’t know where to start.

I tried searching the Internet for a good guide to getting started with ICriteria, but the only examples I found are too simplified to apply here or too advanced for me to understand. If someone has good training materials, they will be very grateful.

In any case, the object model that I am referring to looks like this (significantly simplified, optional properties are omitted):

class Ticket {
    IEnumerable<TicketAction> Actions { get; set; }
}
abstract class TicketAction {
    Person TakenBy { get; set; }
    DateTime Timestamp { get; set; }
}
class CreateAction : TicketAction {}
class Person {
    string Name { get; set; }
}

A Tickethas a set TicketActiondescribing its story. Subtypes TicketActioninclude CreateAction, ReassignAction, CloseActionetc. All tickets have CreateActionadded to this collection at creation.

This LINQ query searches for tickets created by someone with the specified name.

var createdByName = "john".ToUpper();
var tickets = _session.Query<Ticket>()
    .Where(t => t.Actions
        .OfType<CreateAction>()
        .Any(a => a.TakenBy.Name.ToUpper().Contains(createdByName));

The method OfType<T>()causes an outlier NotSupportedException. Can I do this with ICriteria?

+5
source share
2 answers

- . , , IEnumerable<TicketAction> Actions Person TakenBy . , .

Ticket TicketAction, - :

ICriteria criteria = _session.CreateCriteria(typeof(CreateAction))
   .Add(Expression.Eq("TakenBy.Name", createdByName));

var actions = criteria.List<CreateAction>();

var results = from a in criteria.List<>()
   select a.Ticket;

, nhibernate , , - , . , Expression.Eq. linq, , , linq, , .

+2

OfType. , ToUpper , , SQL , ( , ...). unit test nHibernate.LINQ:

var animals = (from animal in session.Linq<Animal>()
               where animal.Children.OfType<Mammal>().Any(m => m.Pregnant)
               select animal).ToArray();
Assert.AreEqual("789", animals.Single().SerialNumber);

, :

var animals = (from ticket in session.Linq<Ticket>()
               where ticket.Actions.OfType<CreateAction>().Any(m => m.TakenBy.Name.Contains("john"))
               select ticket).ToArray();
0

All Articles