NHibernate Lambda Extensions - CreateCriteria Issue - nhibernate

I want to convert a NHibernate CreateCriteria over to a NHLambdaExtensions criteria, but I'm getting errors that I don't know how to fix.
The NHibernate criteria looks like this:
var departments = DepartmentService
.CreateCriteria()
.CreateAlias( "Goals", "goal" )
.Add( Expression.Eq( "goal.Company.Id", companyId ) )
.Add( Expression.Eq( "goal.Program.Id", programId ) )
.List<Business.Department>();
The NHLambdaExtensions criteria that I'm trying to create looks like this:
Business.Goal goalAlias = null;
var departments = DepartmentService
.CreateCriteria()
.CreateAlias<Business.Goal>( g => g.Department, () => goalAlias )
.Add<Business.Goal>( g => g.Company.Id == companyId )
.Add<Business.Goal>( g => g.Program.Id == programId )
.List<Business.Department>();
The error I'm getting is "Could not resolve property Department of: Business.Department". The error obviously has to do with "g => g.Department", and there is nothing in the original NHibernate query that has something similar, but there are no overloads that don't take the expression.

Business.Goal goalAlias = null;
var departments = DepartmentService
.CreateCriteria(typeof(Business.Department)) // need to specify the first criteria as Business.Department
.CreateCriteria<Business.Department>(d => d.Goals, () => goalAlias)
.Add<Business.Goal>( g => g.Company.Id == companyId )
.Add<Business.Goal>( g => g.Program.Id == programId )
.List<Business.Department>();
Look for "Create Criteria Association With Alias" in NHibernate Lambda Extensions (V1.0.0.0) - Documentation
EDIT:
You can actually write this more efficiently as:
// no alias necessary
var departments = DepartmentService
.CreateCriteria<Business.Department>()
.CreateCriteria<Business.Department>(d => d.Goals)
.Add<Business.Goal>( g => g.Company.Id == companyId )
.Add<Business.Goal>( g => g.Program.Id == programId )
.List<Business.Department>();

I haven't used NHLambdaExpressions (but it looks pretty cool and I'll definitely check it out soon), so I'm just guessing here. Could you do something like this:
Business.Goal goalAlias = null;
var departments = DepartmentService
.CreateCriteria()
.CreateCriteria((Business.Department g) => g.Goals, () => goalAlias)
.Add<Business.Goal>( g => g.Company.Id == companyId )
.Add<Business.Goal>( g => g.Program.Id == programId )
.List<Business.Department>();
I think this will root a new criteria at Goals and assign an alias via goalAlias.

Related

Multiple Subqueries With QueryOver

I need help converting this sql query into QueryOver Nhibernate criteria.
select distinct * from event e where e.name like '%req%'
or e.Id in (select r.eventId from requirement r where r.name like '%req%')
or e.Id in (select r.eventId from requirement r where r.id
in (select s.requirementId from solution s where s.name like '%sol%'))
var queryOver = session.QueryOver<Event>()
.Where(x => x.Name.IsInsensitiveLike("%"+searchTerms[1]+"%"))
.OrderBy(x => x.CreatedOn).Asc;
So far I have the main query but couldn't find enough reference material on how to add the subqueries. Haven't been successful using joinQueryOver.
Event has one-to-many rel with requirement and requirement has one-to-many rel with solution.
Requirement reqAlias = null;
Solution solAlias = null;
var subQuery = QueryOver.Of<Event>()
.JoinAlias(x => x.Requirements, () => reqAlias)
.Where(x => x.Name.IsInsensitiveLike(searchTerms[2]))
.JoinAlias(() => reqAlias.Solutions, () => solAlias)
.Where(x => x.Name.IsInsensitiveLike(searchTerms[3]))
.Select(Projections.Group<Event>(x => x.Id));
var events = session.QueryOver<Event>()
.Where(x => x.Name.IsInsensitiveLike(searchTerms[1]))
.WithSubquery.WhereProperty(x => x.Id).In(subQuery)
.List().ToList();
still not working.
When you use IsInsensitiveLike NHibernate appends the % after parsing, and uses lower to do a lower case comparison. In your code, you are appending the % yourself, which results in,
select distinct * from event e where e.name like %lower('%req%')%
which in turn, doesn't work.
Also, you have 3 subqueries, no a big one, so you need to restructure your code to account for that:
select r.eventId from requirement r where r.name like '%req%'
to
var firstQuery = QueryOver.Of<Requirement>()
.Where(r => r.Name.IsInsensitiveLike(searchTerms[2]))
.Select(r => r.EventId);
then,
select s.requirementId from solution s where s.name like '%sol%'
to
var solutionQuery = QueryOver.Of<Solution>()
.Where(s => s.Name.IsInsensitiveLike(searchTerms[3]));
then,
select r.eventId from requirement r where r.id
in (select s.requirementId from solution s where s.name like '%sol%')
to
var requirementQuery = QueryOver.Of<Requirement>()
.WithSubquery
.WhereProperty(r => r.Id).In(solutionQuery)
.Select(r => r.EventId);
Then you need to construct the main query using Restrictions.Or to include the 3 queries.

Fluent Nhibernate QueryOver and Joins

I'm in the process of learning Fluent nHibernate. I'm having trouble with building a query thats not quite the same as the classic examples I've found online. Typically I've found this example:
IQueryOver<Cat,Cat> catQuery =
session.QueryOver<Cat>(() => catAlias)
.JoinAlias(() => catAlias.Kittens, () => kittenAlias)
.Where(() => catAlias.Age > 5)
.And(() => kittenAlias.Name == "Tiddles");
So from what I understand in this example a Cat object is being returned after being joined on Kittens and then filtered using the kittens name and the cat's age. And the join works because the Cat object has a property called Kittens.
An example of what I'm trying to do would look like this:
Forest f = null;
Tree t = null;
ForestsFound = session.QueryOver<Forest>(() => f)
.JoinAlias(() => t.Forest, () => f)
.Where(() => t.NumberOfTrees > 1000)
.List<Forest>()
.ToList<Forest>();
A forest is essentially a lookup table, it's the Tree that has a link to what forest the tree is in but I want to return a distinct list of forests. So in regular sql it would look like:
select f.*
from Forest f
inner join Tree t
on t.Forest_id = f.ID
where t.NumberOfTrees > 1000
If you have a relationship from Forest -> Trees then you can do this:
Forest f = null;
Tree t = null;
ForestsFound = session.QueryOver<Forest>(() => f)
.JoinAlias(() => f.Trees, () => t)
.Where(() => t.NumberOfTrees > 1000)
.List<Forest>();

Duplicated and unnecessary joins when using Linq in NHibernate

Basically I crossed the same problem of Linq provider in this linq-to-nhibernate-produces-unnecessary-joins
List<Competitions> dtoCompetitions;
dtoCompetitions = (from compset in session.Query<FWBCompetitionSet>()
where compset.HeadLine == true
&& compset.A.B.CurrentSeason == true
select (new Competitions
{
CompetitionSetID = compset.CompetitionSetID,
Name = compset.Name,
Description = compset.Description,
Area = compset.Area,
Type = compset.Type,
CurrentSeason = compset.A.B.CurrentSeason,
StartDate = compset.StartDate
}
)).ToList();
Which leads to duplicated join in its generated SQL
SELECT fwbcompeti0_.competitionsetid AS col_0_0_,
fwbcompeti0_.name AS col_1_0_,
fwbcompeti0_.DESCRIPTION AS col_2_0_,
fwbcompeti0_.area AS col_3_0_,
fwbcompeti0_.TYPE AS col_4_0_,
fwbseason3_.currentseason AS col_5_0_,
fwbcompeti0_.startdate AS col_6_0_
FROM fwbcompetitionset fwbcompeti0_
INNER JOIN A fwbcompeti1_
ON fwbcompeti0_.competitionseasonid = fwbcompeti1_.competitionseasonid
INNER JOIN A fwbcompeti2_
ON fwbcompeti0_.competitionseasonid = fwbcompeti2_.competitionseasonid
INNER JOIN B fwbseason3_
ON fwbcompeti2_.seasonid = fwbseason3_.seasonid
WHERE fwbcompeti0_.headline = #p0
AND fwbseason3_.currentseason = #p1
Notice these joins, which are totally duplicated and also affect my SQL Server's performence.
INNER JOIN A fwbcompeti1_
ON fwbcompeti0_.competitionseasonid = fwbcompeti1_.competitionseasonid
INNER JOIN A fwbcompeti2_
ON fwbcompeti0_.competitionseasonid = fwbcompeti2_.competitionseasonid
Update1
In the NHibernate 3.2, this LiNQ bug is still valid, and I could not find a simple and reasonable Linq solution.
So I used QueryOver + JoinAlias + TransformUsing finishing the job, workds perfect to me.
FWBCompetitionSet compset = null;
FWBCompetitionSeason compseason = null;
FWBSeason season = null;
IList<Competitions> dtoCompetitions;
dtoCompetitions = session.QueryOver<FWBCompetitionSet>(() => compset)
.JoinAlias(() => compset.FWBCompetitionSeason, () => compseason)
.JoinAlias(() => compseason.FWBSeason, () => season)
.Where(() => compset.HeadLine == true)
.And(() => season.CurrentSeason == true)
.SelectList(
list => list
.Select(c => c.CompetitionSetID).WithAlias(() => compset.CompetitionSetID)
.Select(c => c.Name).WithAlias(() => compset.Name)
.Select(c => c.Description).WithAlias(() => compset.Description)
.Select(c => c.Area).WithAlias(() => compset.Area)
.Select(c => c.Type).WithAlias(() => compset.Type)
.Select(c => season.CurrentSeason).WithAlias(() => season.CurrentSeason)
.Select(c => c.StartDate).WithAlias(() => compset.StartDate)
)
.TransformUsing(Transformers.AliasToBean<Competitions>())
.List<Competitions>();
Yet Another Edit:
I think I finally found out what's going on. It seems that the LINQ to NHibernate provider has trouble navigating associations from the target to the source table and generates a separate join each time it encounters such an association.
Since you don't provide your mapping, I used the mapping from linq-to-nhibernate-produces-unnecessary-joins. This model has a Document with one Job and many TranslationUnits. Each TranslationUnit has many Translation entities.
When you try to find a Translation based on a Job, you are traversing the associations in the reverse order and the LINQ provider generates multiple joins: one for Translation -> TranslationUnit and one for TranslationUnit to Document.
This query will generate redundant joins:
session.Query<TmTranslation>()
.Where(x => x.TranslationUnit.Document.Job == job)
.OrderBy(x => x.Id)
.ToList();
If you reverse the navigation order to Document -> TranslationUnit -> Translation, you get a query that doesn't produce any redundant joins:
var items=(from doc in session.Query<Document>()
from tu in doc.TranslationUnits
from translation in tu.Translations
where doc.Job ==job
orderby translation.Id
select translation).ToList();
Given this quirkiness, QueryOver seems like a better option.
Previous Edit:
I suspect the culprit is compset.A.B.CurrentSeason. The first joined table (fwbcompeti1_) returns A.B while the next two (fwbcompeti2_ and fwbseason3_) are used to return A.B. The LINQ to NHibernate provider doesn't seem to guess that A is not used anywhere else and fails to remove it from the generated statement.
Try to help the optimizer a little by replacing CurrentSeason = compset.A.B.CurrentSeason with CurrentSeason = true from the select, since your where statement returns only items with CurrentSeason == true.
EDIT: What I mean is to change the query like this:
List<Competitions> dtoCompetitions;
dtoCompetitions = (from compset in session.Query<FWBCompetitionSet>()
where compset.HeadLine == true
&& compset.A.B.CurrentSeason == true
select (new Competitions
{
CompetitionSetID = compset.CompetitionSetID,
Name = compset.Name,
Description = compset.Description,
Area = compset.Area,
Type = compset.Type,
CurrentSeason = true,
StartDate = compset.StartDate
}
)).ToList();
I simply replace the value compset.A.B.CurrentSeason with true

NHIbernate fetch returning multiple parent objects

Can anyone explain why this query would return 12 companies (it has 12 UserAccessList children)
var list = session.QueryOver<Company>()
.Where(x => x.Id == 1) //x => x.Id.IsIn(ids))
.Fetch(l => l.UserAccessList).Eager()
.List<Company>();
Because in SQL its going to be something like:
select * from
Companies c left outer join UserAccessLists uac on c.Id == uac.CompanyId
where c.id = id
And it is giving duplicates in results. How to fix such issues you can read here.
This also works
var c = session.QueryOver<Company>()
.Future();
session.QueryOver<Company>()
.Fetch(l => l.UserAccessList).Eager()
.Future();
var list = c.ToList();

QueryOver with Select and OrderBy in NHibernate

I am wondering how do I order a group of results after a select with QueryOver. My query is the following:
CurrentSession.QueryOver<Book>()
.Where(b => b.Author.Name = "SimpleName")
.Select(Projections.Distinct(Projections.Property<Book>(b => b.Genre)))
.OrderBy<Genre>(g => g.Name) // this extension does not exist! How do I order for a Genre?
.List<Genre>()
How can I do?
Your query won't work to begin with. You first of all need to do a join, then you can do your order by and select projections.
Author author = null;
Genre genre = null;
CurrentSession.QueryOver<Book>()
.JoinAlias(b => b.Author, author)
.JoinAlias(b => b.Genre, genre)
.Where(() => author.Name == "SimpleName")
.OrderBy(() => genre.Name)
.Select(Projections.Distinct(Projections.Property<Book>(b => b.Genre)))
.List<Genre>();