NHibernate QueryOver Where with internal select - nhibernate

I have a problem with translating this SQL into QueryOver notation. Can you help me?
SELECT * FROM Alerts a
WHERE a.CreatedOn = (
SELECT MAX(b.CreatedOn) FROM Alerts b WHERE b.UserFk=a.UserFk);
I try to select last alert for every user. I use CreatedOn and cannot use Id.
I have so far:
session.QueryOver(() => alertAlias)
.SelectList(list => list
.Select(() => alertAlias.User.Id)
.SelectSubQuery(
QueryOver.Of<Alerts>()
.Where(x => x.User.Id == alertAlias.User.Id)
.OrderBy(x => x.CreatedOn).Desc
.Select(x => x.CreatedOn)
.Take(1)));
I know it adds user's last alert date to every user's alert row. But I want to have only last alerts.

Your attempt is using subquery inside of a SELECT statement. But we need to move it into WHERE. This should be the way:
// this is a subquery (SELECT ....
var subquery = QueryOver.Of<Alerts>()
.Where(x => x.User.Id == alertAlias.User.Id)
.OrderBy(x => x.CreatedOn).Desc
.Select(x => x.CreatedOn)
.Take(1)));
// main Query could now have or do not have that subquery selected
var query = session.QueryOver(() => alertAlias)
.SelectList(list => list
.Select(() => alertAlias.User.Id)
// could be there
.SelectSubQuery(subquery)
)
// but mostly here we do use WHERE clause
.WithSubquery
.WhereProperty(() => alertAlias.CreatedOn)
.Eq(subquery)
;
// such a query could be returned as a list of arrays
var results = query.List<object[]>();
We can also use some Result Transformer, but this is another story...

Related

How to convert my partial In Memory LINQ GroupBy query to complete Database Query or should I use raw sql?

I tried different ways to solve this but either it wont let me include or it gives error for the GroupBy statement.
In the above code, I am trying to Group the MedicineEquipments by FOREIGN KEY i.e LocationId, and take the latest record with that LocationId and also include Location and MedicineEquipmentNavigation along with the record.
var medicineEquipmentShops = await dbContext.MedicineEquipments
.Where(x => x.CityId == cityId && x.MedicineEquipmentId == medicineEquippmentId)
.Include(x => x.Location)
.Include(x =>x.MedicineEquipmentNavigation)
.ToListAsync();
medicineEquipmentShops = medicineEquipmentShops.GroupBy(x => x.LocationId)
.Select(x => x.OrderByDescending(y => y.UpdatedOn).FirstOrDefault())
.OrderByDescending(x => x.IsVerified)
.ThenByDescending(x => x.Stock)
.ThenByDescending(x => x.Votes)
.ToList();

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();

QueryOver, GroupBy and Subselect

how can I do this with queryover and a subquery?
FakturaObjektGutschrift fog = null;
int[] idS = Session.QueryOver(() => fog)
.SelectList( list => list
.SelectMax(() => fog.Id)
.SelectGroup(() => fog.SammelKontierung)
).List<object[]>().Select(x => (int)x[0]).ToArray();
And using the ids in another query
IQueryOver<Beleg, Beleg> sdfsd = Session.QueryOver(() => bGut)
.AndRestrictionOn(() => fog.Id).IsIn(idS); //iDs is a list of int.
I would like do this with a subquery because there is a limitation on the number of parameters for a SQL query. How do I do this?
How do I write the first query, but without selecting the SelectGroup()? This is exactly where I got stuck.
Group by without projection in QueryOver API is currently not supported link.
You can use LINQ to create the projection in a subquery:
var subquery = Session.Query<FakturaObjektGutschrift>()
.GroupBy(x => x.SammelKontierung)
.Select(x => x.Max(y => y.Id));
var query = Session.Query<Beleg>()
.Where(x => subquery.Contains(x.Id));
If you really needs QueryOver to create more complex queries check this solution link.

NHibernate QueryOver with JoinQueryOver select all columns

I have some QueryOver with several joins and the result I get is OK in terms of the returned objects. This is the code>
var l = session.QueryOver<Discount>(() => discount)
.JoinQueryOver<ConPrdGrp>(r => r.ConPrdGrps)
.JoinQueryOver<PrdGroupTree>(k => k.PrdGroupTree)
.JoinQueryOver<Product>(g => g.Products)
.Where(p => p.ProductID == Product.ProductID)
.And(() => discount.FomDato <= DateTime.Now && discount.TomDato >= DateTime.Now).List();
But if I look at the SQL statement, I can see that the generated query selects ALL columns from all joined tables although the result only returns a list of Discount objects. I can get some properties of Discount using projections and the query will be much smaller. But how I can instruct NHibernate to get just columns from the Discount table and not from all joined tables?
As far as I know there is NOT a simple way like: .Select(Projections.Properties<Discount>()). Check this a bit outdated question (NHIbernate: Shortcut for projecting all properties?)
What you can do is explicitly name the columns you would like to see:
... // the QueryOver you have
.SelectList (l => l
.Select(() => discount.ID).WithAlias(() => discount.ID)
.Select(() => discount.Code).WithAlias(() => discount.Code)
...
)
.TransformUsing(Transformers.AliasToBean<Discount>())
...
The second approach could be to create the Subquery, and then just QueryOver<Discount>() 16.8. Subqueries
QueryOver<Discount> subQuery =
QueryOver.Of<Discount>(() => innerDiscount)
.JoinQueryOver<ConPrdGrp>(r => r.ConPrdGrps)
.JoinQueryOver<PrdGroupTree>(k => k.PrdGroupTree)
.JoinQueryOver<Product>(g => g.Products)
.Where(p => p.ProductID == Product.ProductID)
.And(() => innerDiscount.FomDato <= DateTime.Now
&& innerDiscount.TomDato >= DateTime.Now).List()
.Select( Projections.Property(() => innerDiscount.ID))
;
var query = session.QueryOver<Discount>(() => discount)
.Where(Subqueries.PropertyIn("ID", subQuery.DetachedCriteria))
;

NHibernate multi table query returning same row more than once

The following nhibernate query is causing me issues because it returns the same row more that once as the child tables have more than one row that match the criteria supplied. What i would like to know is the most efficient/ best practice in nhibernate to do this same query but to only get each row in DataMappingBase once. Returning multiple of the same row is breaking my number of results returned as i try to limit it 25 but sometimes i get the same row 25 times.
MappedID id = null;
DataMappingBase mapBase = null;
NameDetails name = null;
dmbs = mappingSession.QueryOver<DataMappingBase>(() => mapBase)
.JoinAlias(() => mapBase.IDs, () => id).WhereRestrictionOn(() => id.SecondaryDataIDType).IsNull()
.JoinAlias(() => mapBase.Names, () => name).WhereRestrictionOn(() => name.Name).IsInsensitiveLike(request.Filter, MatchMode.Anywhere)
.Take(request.MaxResults)
.List();
i am currently looking at converting the query above to a detached query and removing the "take" clause and getting it to just return the ID of the matching rows and have it used in a sub-query selecting from "DataMappingBase" where the rows ID is in the ids returned by the sub-query but i am not sure if that is the best way or not.
I'm not sure, but you can do like this:
MappedID id = null;
DataMappingBase mapBase = null;
NameDetails name = null;
dmbs = mappingSession.QueryOver<DataMappingBase>(() => mapBase)
.JoinAlias(() => mapBase.IDs, () => id).WhereRestrictionOn(() => id.SecondaryDataIDType).IsNull()
.JoinAlias(() => mapBase.Names, () => name).WhereRestrictionOn(() => name.Name).IsInsensitiveLike(request.Filter, MatchMode.Anywhere)
.Take(request.MaxResults)
// add this
.TransformUsing(Transformers.DistinctRootEntity)
.List();