NHibernate Fetch / ThenFetch for joined siblings - linq

I have the following (simplified) hierarchy of entities:
RootClass
->DescriptorClass
->SomeChild->DescriptorClass
->SomeGrandChild
I would like to fetch everything in a single query, if possible.
Currently I have the following:
Session.Query<RootClass>().Where(/*some expressions here*/)
.Fetch(v => v.DescriptorClass)
.Fetch(v => v.SomeChild).ThenFetch(v => v.SomeGrandChild)
.Fetch(v => v.SomeChild).ThenFetch(v => v.DescriptorClass);
it works fine but it creates an SQL query with two joins on SomeChild. Obviously, I have to get rid of that second Fetch(v => v.SomeChild) but I cannot find how to do it.
I tried:
Session.Query<RootClass>().Where(/*some expressions here*/)
.Fetch(v => v.DescriptorClass)
.Fetch(v => v.SomeChild).ThenFetch(v => v.SomeGrandChild)
.ThenFetch(v => v.DescriptorClass); //<- wrong, tries to find DescriptorClass on SomeGranchild
and
Session.Query<RootClass>().Where(/*some expressions here*/)
.Fetch(v => v.DescriptorClass)
.Fetch(v => v.SomeChild).ThenFetch(v => v.SomeGrandChild)
.Fetch(v => v.DescriptorClass); //<- wrong, loads the same DescriptorClass of RootClass, not on SomeChild
How do I tell NHibernate to create a single join on SomeChild and then fetch SomeGrandChild and DescriptorClass of SomeChild?

For this type of query, switch to using the LINQ query syntax instead of lambdas as it gives you more control and typically outputs more efficient and cleaner SQL.
Take a look at the sample below and notice how I am able to reference the Customer entity multiple times by using the alias 'c'.
var customers =
(
from c in session.Query<Customer>()
from a in c.Addresses
from pn in c.PhoneNumbers
where c.Status == "Active"
&& a.City == "Dallas"
&& pn.AreaCode == "972"
select c )
.ToList();
This will result in the following SQL using NHibernate:
SELECT
customer0_.CustomerId as Customer1_135_0_,
customer0_.Status as Customer1_135_1_
FROM
Customer customer0_
INNER JOIN
CustomerAddresses customeraddr1_
ON customer0_.CustomerId=customeraddr1_.CustomerId
INNER JOIN
CustomerPhoneNumbers customerphon2_
ON customer0_.CustomerId=customerphon2_.CustomerId
WHERE
customer0_.Status='Active' /* #p0 */
AND customeraddr1_.City = 'Dallas' /* #p1 */
AND customerphon2_.AreaCode = '972' /* #p2 */;

Related

Which of these LINQ queries performs better?

In the context of Entity Framework, which of these queries performs better?
var result = Items.OrderByDescending(t => t.Created)
.FirstOrDefault(a => a.ID == ItemID)?.ItemName;
or
var result = Items.Where(a => a.ID == ItemID)
.OrderByDescending(t => t.Created)
.FirstOrDefault()?.ItemName;
Is there anywhere I can read about how these LINQ queries are converted to SQL in this case.

Select two lists as one list in ASP.NET Core linq

I am trying to create a query with ASP.NET Core EF Core and Linq that would give me a List of users based on two different lists, something like this:
return await _context.Users
.Include(u => u.PropertyOwners)
.ThenInclude(po => po.Property)
.ThenInclude(p => p.PropertyTenantLeases)
.Include(u => u.PropertyOwners)
.ThenInclude(po => po.Owner)
.Where(u => u.Id == userID)
.Select(u => new List<User>()
{
u.PropertyTenantLeases.Select(ptl => ptl.Tenant).ToList()
u.PropertyOwners.Select(po => po.Owner).ToList()
}).FirstOrDefaultAsync();
The tables that are used in this query are connected in the following way:
Everything is fine with this query except for the Select, with the Select I am trying to achieve that it returns a list of all the tenants in the PropertyTenantLeases table which is a junction table togheter with all the Owners form the PropertyOwners junction table (both Tenant and Owner are IdentityUser classes. When I right this query like this I get the following error:
The best overloeaded Add method 'List<User>.Add(User)' for the collection initializer has some invalid arguments
and also
Argument 1: cannot convert from 'System.Collections.Generic.List<RosyMasterDBManagement.Models.User>' to 'RosyMasterDBManagement.Models.User'
Joining two list is called a union in Linq -- I believe that is what you want:
note: I still can't test this since you gave a picture of the data model instead of the code that would allow me to be certain of how to implement. expect the fields to be named incorrectly etc.
var ownerlist = _context.Users
.Include(u => u.PropertyOwners)
.ThenInclude(po => po.Owner)
.ToList();
var tenantlist = _context.Users
.Include(u => u.PropertyOwners)
.ThenInclude(po => po.Property)
.ThenInclude(p => p.PropertyTenantLeases)
.ThenInclude(po => po.Tenant)
.ToList();
return ownerlist.Union(tenantlist);
I don't believe you need await() since ToList() forces it to not be lazy. But I could be wrong about that.

Where in clause using linq

trying to convert a query which has 2 levels of where in clauses to linq and getting some errors. Can anybody help me on this?
Original Query:
select id
from student
where suId
in (select suId
from subjects
where cid
in (select id
from chapters
where chapter='C203'))
LINQ query:
var query = (from s in dc.students
let subs = (from su in dc.subjects
where su.cid == Convert.ToInt32(from c in dc.Chapters
where c.chapter == 'Ç203'
select c.id) //Single chapter id will be returned
select su.suid)
where subs.Contains(s.sid)
select s.id).ToArray();
Am getting below 2 errors while compiling app
'System.Linq.IQueryable' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.ParallelEnumerable.Contains(System.Linq.ParallelQuery, TSource)' has some invalid arguments
Instance argument: cannot convert from 'System.Linq.IQueryable' to 'System.Linq.ParallelQuery'
Since Linq is lazy-loading everything you don't need to cram everything into a single statement; you can do something like this:
var chapterIds = dc.Chapters
.Where(c => c.Chapter == "C023")
.Select(c => c.Id);
var subjectIds = dc.Subjects
.Where(s => chapterIds.Contains(s.Cid))
.Select(s => s.Suid);
var students = dc.Students
.Where(s => subjectIds.Contains(s.Suid))
.Select(s => s.Sid)
.ToArray();
This way you can debug each subquery by looking at what it returns.
However, looking at your original select you can rewrite the whole thing as a Join and get rid of the bugging issue:
var students = dc.Chapters.Where(c => c.Chapter == "C023")
.Join(dc.Subjects,
c => c.Id,
s => s.Cid,
(chapter, subject) => subject)
.Join(dc.Students,
subj => subj.Suid,
student => student.Suid,
(subj, st) => st.Sid)
.ToArray();

What is the lambda equivalent of this Linq query?

What is the equivalent lambda syntax to this linq query?
Dim query = From t In _rdsqlconn.Tags Where t.TagWord = tag
Join p In _rdsqlconn.Posts On t.PostId Equals p.PostId Order By p.PostDatePublished
Descending Select p Where p.PostIsPublished = True
You can do this with a join, like so:
_rdsqlconn.Tags
.Where(t => t.TagWord == tag)
.Join(_rdsqlconn.Posts, t => t.PostId, p => p.PostId, (t, p) => p)
.Where(p => p.PostIsPublished == true)
.OrderByDescending(p => p.PostDatePublished)
but what you want to do is properly map your tables and relationships in the LINQ-to-SQL designer, and then you can use
_rdsqlconn.Posts.Where(p => p.PostIsPublished && p.Tags.Any(t => t.TagWord == tag))
.OrderByDescending(p => p.PostDatePublished)
If you have a foreign key between Posts and Tags in your database then you will be able to do this. It's much cleaner code, and removes the unnecessarily Join operator.

LInq Order By and Order By Desc

I am using "Linq" to filter list of objects and to sort them, like
myList.Where(x => x.Item!= "SF" && x.AdSize == minadSize)
.OrderBy(x => x.ManufacturingDate)
.OrderBy(x=>x.ExpiryDate);
I doubt whether i am doing it right or not that is if i want to "sorting" on multiple fields then is it necessary to use multiple Order By clause cant it be done with single "OrderBy"
Don't use multiple OrderBy calls - use OrderBy followed by ThenBy:
var query = myList.Where(x => x.Item!= "SF" && x.AdSize == minadSize)
.OrderBy(x => x.ManufacturingDate)
.ThenBy(x => x.ExpiryDate); // Could add more ThenBy calls
If you use OrderBy twice, it will reorder the already-ordered-by-date list by expiry-date, whereas I assume you only want to order by expiry date for items with an equal manufacturing date, which is what the above does.
Obviously there's a ThenByDescending method too. For example:
var query = people.OrderBy(x => x.LastName)
.ThenBy(x => x.FirstName)
.ThenByDescending(x => x.Age)
.ThenBy(x => x.SocialSecurity);

Resources