Linq to nhibernate - Having where clause problems - nhibernate

I am using linq-to-nhibernate with the following query:
ISession session = GetSession();
var query = from storeZoneStyles in session.Linq<StoreZoneStyle>()
from storeZones in session.Linq<StoreZone>()
where storeZoneStyles.StoreZoneId == storeZones.StoreZoneId && storeZones.StoreCode == storeCode
select storeZoneStyles;
With this query, I only want to get all storeZoneStyles that belong to a storecode. Now when I run this I get the following run-time exception:
Unable to cast object of type 'System.Linq.Expressions.ConstantExpression' to type 'System.Linq.Expressions.LambdaExpression'.
Can somebody help me out please?

I had to use this query instead, because joins are not supported in L2N
var query = from storeZoneStyles in session.Linq<StoreZoneStyle>()
where storeZoneStyles.Zone.StoreCode == storeCode
select storeZoneStyles;

Related

nhibernate hql subquery : convert null to zero

I am trying to update sum of particular amount from one table as a value in another table, but getting problem when the particular id does not exist in another table :
the hql i have looks like beow:
var session = SessionManager.GetCurrentSession();
var queryString = string.Empty;
queryString += #"update CLiner cl set cl.UnbilledDue =
(select sum(cu.UnbilledAmount) as UnbilledAmount from CUnbilled cu
where cu.AccountNo = cl.AccountNo and cu.FileDate = :fileDate)
where cl.FileDate = :fileDate ";
var query = session.CreateQuery(queryString);
query.SetDateTime("fileDate", new DateTime(2014, 10, 7));
query.ExecuteUpdate();
but its giving exception when the particular account no does not exist in child table and the sum is returned as zero.
i tried changing the subquery select to
select isnull(sum(cu.UnbilledAmount),0) as UnbilledAmount
which as expected is not supported by nhibernate hql. so there a way i can convert null to zero in hql select statement...
Try this:
coalesce(sum(cu.UnbilledAccount), 0)
Reason:
Normally when you wirte a SQL query to prevent NULL you must apply an ISNULL function over the SELECT, in this way:
ISNULL(SELECT sum(...., 0) or COALESCE(SELECT sum(...., 0) (return the same result but COALESCE can applied with more parameter, ISNULL has only two parameters)
but in HQL isn't possible, so you can use COALESCE function to prevent that behaviour.

How to get the latest/last record with a group by clause with NHibernate Linq provider

I have used too much time (days) on this and I really hope someone can help me out.
I found a good article on describing my problem in a generic way so let's stick to it.
I am trying to build this query but NHibernate fails to build the correct sql and returns a sql query exception.
Column vSagsAendring.Id is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. It could not execute the following query:
select
viewsagsae0_.Id as Id155_,
viewsagsae0_.SagId as SagId155_,
viewsagsae0_.JournalNr as JournalNr155_,
viewsagsae0_.LbfNr as LbfNr155_,
viewsagsae0_.OrgNr as OrgNr155_,
viewsagsae0_.OrgNavn as OrgNavn155_,
viewsagsae0_.AfdNavn as AfdNavn155_,
viewsagsae0_.SagsType as SagsType155_,
viewsagsae0_.Status as Status155_,
viewsagsae0_.SagsbehandlerInit as Sagsbeh10_155_,
viewsagsae0_.Dato as Dato155_,
viewsagsae0_.JournalAktionType as Journal12_155_,
viewsagsae0_.Beskrivelse as Beskriv13_155_,
viewsagsae0_.Ekstern as Ekstern155_
from vSagsAendring viewsagsae0_
group by viewsagsae0_.SagId
var query = from p in _session.Query<ViewSagsAendring>()
group p by p.SagId
into grp
select grp.OrderByDescending(g => g.Dato).First();
This is another version also took from the article:
var query = from p in _session.Query<ViewSagsAendring>()
group p by p.SagId
into grp
let maxDato = grp.Max(g => g.Dato)
from p in grp
where p.Dato == maxDato
select p;
It's have been a long journey, but now it's over. I hope that I can help someone else in the same situation by answering my own question.
var aendring = from sagsAendring in _session.Query<ViewSagsAendring>()
where sagsAendring.Dato ==
(
from innersagsAendring in _session.Query<ViewSagsAendring>()
where innersagsAendring.SagId == sagsAendring.SagId
select innersagsAendring.Dato
).Max()
select sagsAendring;
var result = aendring.ToList();
And because you can chain linq statements you can build a linq filter like this
if(Filters.VisInterneAendringer == false)
query = query.Where(x => x.Ekstern == true);
if (Filters.VisKunNyesteAendringer)
{
query = query.Where(sagsAendring => sagsAendring.Dato ==
(
from innerSagsAendring in Session.Query<ViewSagsAendring>() where innerSagsAendring.SagId == sagsAendring.SagId
select innerSagsAendring.Dato
).Max());
}
return query;
Your queries seem legit for LINQ in EntityFramework.
I'm not sure about hibernate, you might try to use QueryOver API instead of Query
http://nhibernate.info/blog/2009/12/17/queryover-in-nh-3-0.html

NHibernate IQueryOver where clause with a collection

I'm attemping to do a simple check for an empty collection in an NHIbernate Query. Here's my code:
var query = QueryNotDeleted().Where(x=>x.Markets.Count() > 0);
QueryNotDeleted returns an IQueryOver. The above line throws an error (Unrecognised method call in epression x.Markets.Count()) because it doesn't recognize the Count() in the query.
I tried
var query = QueryNotDeleted().Where(x=>x.Markets != null);
But unfortunately, Markets is never NULL, so I have to test for a count instead of it being null to get the records I want.
How can I get this "count" syntax correct so that it excludes records where the Markets property is empty?
I was able to get it to work using:
query.RootCriteria.CreateAlias("Markets", "m", JoinType.LeftOuterJoin);
and then
query.RootCriteria.Add(Restrictions.IsNotNull("m.Id"));
If I understand your question correctly you want to get a list of records that don't have corresponding children?
If I wanted to get a list of Orders that have no OrderItems using QueryOver then I would do something like:-
var orders = session.QueryOver<Order>()
.Left.JoinQueryOver(w => w.Items)
.Where(w => w.Order.Id == null);
If this is not the right answer then please can you submit the SQL you are trying to run and the parent/children mappings/.

Linq to sql constantly returns null

I have the following SQL query:
SELECT DISTINCT
Participant.BackgroundTrainingID,
Location.TrainingSite
FROM Registration, ProgramLocation, Participant, Program, Location
WHERE ProgramLocation.LocationID = Location.LocationID
AND ProgramLocation.ProgramID=Registration.ProgramID
AND Registration.ParticipantID=Participant.ParticipantId
I wrote the following LINQ to SQL to match the query above:
var trainingsiteinfo = (from c in db.ProgramLocations
from n in db.Registrations
from l in db.Participants
from h in db.Locations
where c.LocationID == h.LocationID
&& c.ProgramID == n.ProgramID
&& n.ParticipantID == l.ParticipantId
select new {
h.TrainingSite,
l.BackgroundTrainingID }).Distinct();
The SQL query works fine but LINQ constantly returns null.
I use Linqer http://www.sqltolinq.com/ when i get out of ideas :-) Aswell it speeds up conversion jobs.
Make sure your db context isn't going out of scope before you have bound your results. You can test this by adding .ToList() after your .Distinct() to force eager loading of the results.
Your linq code has an unclosed } bracket in the select statement

How can write query to select all information where RawMaterialID=1

i am designing a project in asp.net mvc3.
this is my table
i want to print all information where RawMaterialID=1
please suggest me how should i write query to do this. I am using Entity Framework to access database.
You can use Lambda expression or can use sql syntax.
var results = (from x in dbContext.MaterialTable
where x.RawMaterialID == 1
select x);
Or
var results = dbContext.MaterialTable.Where(r => r.RawMaterialID == 1);
It would be something like
var results = dbContext.MyTable.Where(r => r.RawMaterialID == 1);