QueryOver fails with could not resolve property: - nhibernate

I am using NHibernate 3.0 and was comparing Query and QueryOver
var p = _prepo.Query<Party>()
.Where(c => c.Person.LastName == "Bobby")
.FirstOrDefault();
The above works, I get proxy class for p.Person if I view the object graph.
var p = _prepo.QueryOver<Party>()
.Where(c => c.Person.LastName == "Bobby")
.FirstOrDefault();
This one fails with error ==> could not resolve property: Person.LastName of:
Why?

I'm not familiar with the Linq provider but when using QueryOver you have to use a join to do a query like that:
Example 1
IQueryOver<Cat,Kitten> catQuery =
session.QueryOver<Cat>()
.JoinQueryOver(c => c.Kittens)
.Where(k => k.Name == "Tiddles");
Example 2
Cat catAlias = null;
Kitten kittenAlias = null;
IQueryOver<Cat,Cat> catQuery =
session.QueryOver<Cat>(() => catAlias)
.JoinAlias(() => catAlias.Kittens, () => kittenAlias)
.Where(() => catAlias.Age > 5)
.And(() => kittenAlias.Name == "Tiddles");

It works when you use Linq in this case because the filtering is being done on the client, not in the database. So it is actually the IEnumerable version of Where that is running which is not related to NHibernate.
The QueryOver uses Expression<Func<T,object>> which NHibernate tries to translate to SQL but fails. For reasons unknown to me you must explicitly join using JoinQueryOver or JoinAlias.
Some more info on QueryOver here:
http://nhibernate.info/blog/2009/12/17/queryover-in-nh-3-0.html

Related

Unhandled exception. System.InvalidOperationException: The LINQ expression error by JsonConvert.Deserialize()

I get an error from this code:
var b = content.FormMasterLists.Where(x => x.FormMasterStatus == "pending");
var c = b.Where(x => JsonConvert.DeserializeObject<ApprovalCCB>(x.FormMasterApprovalCcb).Group.SelectMany(x => x.Department).SelectMany(x => x.ApprovalCCBLevel).SelectMany(x => x.Approver).Where(x => x.ApproverEmail == "christ").Any());
But this code runs successfully:
var b = content.FormMasterLists.Where(x => x.FormMasterStatus == "pending").ToList();
var c = b.Where(x => JsonConvert.DeserializeObject<ApprovalCCB>(x.FormMasterApprovalCcb).Group.SelectMany(x => x.Department).SelectMany(x => x.ApprovalCCBLevel).SelectMany(x => x.Approver).Where(x => x.ApproverEmail == "christ").Any());
Is there any way to declare .Where without List()?
Is there any way to declare .Where without List()?
No way in such implementation. EF Core cannot convert JsonConvert.DeserializeObject to the SQL and provide needed filtering on the server side.
So you have to materialise objects to IEnumerable and use client side filtering.
Anyway some databases provide filtering based on JSON content but then you have to create appropriate extension function for EF Core.

Nhibernate Restrictions.In Error

Finally tracked down my error which is a result of the query. I have an nhibernate query using a Restrictions.In. Problem is once query executes if no results returned query throws error immediately. Is there another restriction that I can use. I know if I was writing a linq query I could use the .Any to return bool value and go from there is there something similar I can do in this instance?
carMake is passed in
myQuery.JoinQueryOver(x => x.Car)
.Where(Restrictions.In("VIN",
Trades.Where(x => x.Car.Make.ToLower() == carMake.ToLower())
.Select(x => x.Car.PrimaryVIN)
.ToList()));
Assuming that Trades is a list of objects you can use .WhereRestrictionOn() instead. Try this (I split the code for better readability):
var vinsWithCarMake = Trades
.Where(x => x.Car.Make.ToLower() == carMake.ToLower())
.Select(x => x.Car.PrimaryVIN)
.ToList<string>();
var carAlias = null;
var result = myQuery.JoinAlias(x => x.Car, () => carAlias)
.WhereRestrictionOn(() => carAlias.VIN).IsInG<string>(vinsWithCarMake)
.List();

Nhibernate query<T> / queryover<T> orderby a subquery

I am having issues getting Nhibernate 3.3.2.4000 to generate the correct subquery used in the orderby clause as displayed below:
select *
from dbo.Person p inner join dbo.Task t on p.Task_FK = p.TaskId
order by (select p.CustomerNumber where p.IsMain=1) desc
We have two entities: Task and Person
One task can have N persons related to it. I.e Task has an IList property.
How can I make Nhibernate generate the correct subquery ? I have gotten as far as something like this with the Query API:
query = query.OrderBy(x => x.Persons.Single(t => t.CustomerNumber));
but I am unsure how I can correctly generate the where clause as displayed in the original sql query. Is this perhaps easier done using the queryover api somehow?
Any advice or guidance is most welcome.
Task task = null
Person person = null;
var subquery = QueryOver.Of<Task>()
.Where(t => t.Id == task.Id)
.JoinQueryOver(t => t.Persons, () => person)
.Where(p => p.IsMain)
.Select(() => person.CustomerNumber);
var query = session.QueryOver(() => task)
.OrderBy(Projections.SubQuery(subquery))
.FetchMany(x => x.Persons)
return query.List();

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 queryover with multiple join fail

I have a nhibernate queryover like this:
var query = Session.QueryOver<Immobile>()
.WhereRestrictionOn(i => i.Agenzia.CodiceAgenzia).IsLike(codiceAgenzia)
.WhereRestrictionOn(i => i.StatoImmobile.StatoImmobileId).IsLike(statoId)
.And(i => i.Prezzo <= prezzo)
.And(i => i.Mq <= metriquadri);
The code compile but on execute I receive this exception:
could not resolve property: Agenzia.CodiceAgenzia of: Domain.Model.Immobile
What am I doing wrong?
QueryOver syntax doesnt work that way unfortunately on Referenced objects you need to join them first and then add the restriction..
Change the code to as follows:
Azengia azengiaAlias=null; //Azengia here is typeof(Immobile.Azengia) I am assuming it is Azengia
StatoImmobile statoImmobileAlias=null; //similarly StatoImmobile is assumed to be typeof(Immobile.StatoImmobile)
var query=Session.QueryOver<Immobile>()
.Where(i => i.Prezzo <= prezzo && i.Mq <= metriquadri)
.Inner.JoinAlias(x=>x.Agenzia,()=>azengiaAlias)
.Inner.JoinAlias(x=>x.StatoImmobile,()=.statoImmobileAlias)
.WhereRestrictionOn(() => azengiaAlias.CodiceAgenzia).IsLike(codiceAgenzia)
.WhereRestrictionOn(() => statoImmobileAlias.StatoImmobileId).IsLike(statoId);
Hope this helps.