C# LINQ to SQL - one to many relationship - c#

I have troubles creating this query in LINQ:
USE Northwind
GO
SELECT emp.FirstName, emp.LastName, tr.TerritoryDescription, reg.RegionDescription
FROM Employees emp
INNER JOIN EmployeeTerritories empt ON empt.EmployeeID = emp.EmployeeID
INNER JOIN Territories tr ON tr.TerritoryID = empt.TerritoryID
INNER JOIN Region reg ON reg.RegionID = tr.RegionID
This is my current creation:
var query = await context
.Employees
.Select(x => new
{
x.FirstName,
x.LastName,
TerritoryId = x.EmployeeTerritories. //cannot access properties
})
.ToListAsync();
But i can't easily access EmployeeTerritories properties, since it's not 1:1 relationship. I accept both clues and full solution to this problem.
Edit
So this is what i currently have:
var query = await context
.Employees
.Select(x => new
{
x.FirstName,
x.LastName,
TerritoryDescription = x.EmployeeTerritories
.Select(et => et.Territory.TerritoryDescription)
.ToList(),
RegionDesicription = x.EmployeeTerritories
.Select(et => et.Territory.Region.RegionDescription)
.ToList()
})
.ToListAsync();
Is there a way to optimize it? RegionDescription is now a list that contains one element, but i don't know how to do it the better way.

Try something like this (assuming you have corresponding relations):
var query = await context
.Employees
.Select(x => new
{
x.Employee.FirstName,
x.Employee.LastName,
TerritoryDescription = x.EmployeeTerritories
.Select(et => et.Territory.TerritoryDescription)
.ToList(),
})
.ToListAsync();
UPD
To flatten in your particular case you can use solution posted by #dhrumil shah(it is more generic one) or try something like that, if you have EmployeeTerritories set up in your context :
var query = await context
.EmployeeTerritories
.Select(et => new
{
et.Employee.FirstName,
et.Employee.LastName,
et.Territory.TerritoryDescription,
et.Territory.Region.RegionDescription
})
.ToListAsync();

(from emp in context.Employees
join empt in context.EmployeeTerritories
on emp.EmployeeID equals empt.EmployeeID
join tr in context.EmployeeTerritories
on empt.TerritoryID equals tr.EmployeeID
join reg in context.Region
on reg.RegionID equals tr.RegionID
select new {
emp.FirstName,
emp.LastName,
tr.TerritoryDescription,
reg.RegionDescription
}).ToList();

Related

How can I transalte SQL Query to LINQ

I trying to translate SQL Query to Linq statement:
SELECT f.BarcodeNumber,m.Name, f.Model, SUM(f.Quantity) as FoundedAssetsQty, ISNULL(a.Quantity,0) as AssetQty
FROM [InventoryDB].[dbo].[FoundedAssets] f
join [InventoryDB].[dbo].[PhisicalStockCheckSheets] p on p.ID = f.PhisicalStockCheckSheetId
join [InventoryDB].[dbo].[Inventories] i on i.ID = p.InventoryId
left join [InventoryDB].[dbo].[Assets] a on a.BarcodeNumber = f.BarcodeNumber
join [InventoryDB].[dbo].[Manufacturers] m on m.ID = f.ManufacturerId
where p.InventoryId = 10
group by f.BarcodeNumber, a.Quantity, f.Model, m.Name
I have no idea how to do it. I tried many ways but I fail. Could anyone help me?
I tried to use Linqer, but when I configure the connection it fails, so I write the linq instruction myself. Finally I found the answer. I have not mentioned the relations between entities but it is not important here.
var summary = _context.FoundedAssets.Include(f => f.Manufacturer).
Include(f => f.Asset).
Include(f => f.PhisicalStockCheckSheet).ThenInclude(f => f.Inventory).
Where(f => f.PhisicalStockCheckSheet.Inventory.ID == id).
Select(x => new InventorySummaryModel()
{
BarcodeNumber = x.BarcodeNumber.Value,
ManufacturerName = x.Manufacturer.Name,
Model = x.Model,
AssetsQuantity = x.Asset.Quantity,
FoundedAssetQuantity = x.Quantity
}).ToList();
var groupedSummary = summary.GroupBy(x => x.BarcodeNumber).Select(x => new InventorySummaryModel()
{
BarcodeNumber = x.First().BarcodeNumber,
ManufacturerName = x.First().ManufacturerName,
Model = x.First().Model,
FoundedAssetQuantity = x.Sum(a => a.FoundedAssetQuantity),
AssetsQuantity = x.First().AssetsQuantity
}).ToList();
Maybe exists any easier approach but this one works properly.

Inner join in C# with lambda

I'm new to LINQ and Lambda. I want to make query that will get me for every studyYear (1,2,3) students who are studying that year. I've done it without Lambda but I really want to know how to do it with lambda.
var res = from s in db.student
join u in db.EnrolledYear
on s.ID equals u.studentID
join g in db.studyYear
on u.studyYearID equals g.ID
select new
{
Year = g.year,
StudentFName = s.FirstName
StudentLName = s.LastName
};
I checked out other examples with lambda but I didn't really understand .
What I managed is to make inner join between student and enrolled year. Now I don't understand how to finish inner join between enrolled year and study year.
I'm stuck here, I need to make one more join:
var res = db.EnrolledYear.Join(db.student,
u => u.studentID, s => s.ID,
(enroll, student) => new
{
Godina = enroll.year,
FName = student.FirstName
LName = student.LastName
})
.Join(.....?)
Use Include.
Something like:
db.students.Include(x => x.EnrolledYears).ThenInclude(x=>x.StudyYear).Select(new ...)
Every clause in a query will correspond to a lambda call. Just go down to every clause and convert to an appropriate call.
This particular query could be written like so:
db.student
.Join(db.EnrolledYear, s => s.ID, u => u.studentID, (s, u) => new { s, u })
.Join(db.studyYear, x => x.u.studyYearID, g => g.ID, (x, g) => new { x.s, x.u, g })
.Select(x => new
{
Year = x.g.year,
StudentFName = x.s.FirstName,
StudentLName = x.s.LastName,
});

Perform GroupJoin and Join in single query in Entity Framework Core

I am trying to do a join inside a groupjoin using Linq. Here's the scenario - for each lineitem in an order, I want to get some attributes from the variant for that line item(such as variant options and imageid which are stored in variant and product databases). i want to join lineitem, variant and product databases to get these extra information for the lineitem and then groupjoin this lineitem with the order table. i have done this and got the desired result using two queries but I am not sure how many database queries are run. And in the first case(ie in the join, a limit cannot be specified so I just want to make sure that the first iqueryable in the code below is evaluated only when .ToListAsync() is called). Is this the right way to do it? Any help would be greatly appreciated!
public async Task<dynamic> GetOrdersAsync(User user, int pageNumber = 1)
{
var perPage = 10;
var lineItemAndVariant = from l in _context.LineItems
join v in _context.Variants
on l.EcomPlatformVariantId equals v.EcomPlatformVariantId
join p in _context.Products
on v.ProductId equals p.Id
where p.UserId == user.Id
select new
{
l.Id,
l.OrderId,
l.Price,
l.Quantity,
l.EcomPlatformLineItemId,
l.EcomPlatformVariantId,
l.Title,
ImageId = v.ImageId ?? p.ThumbnailId, // for adding image
p.MyVendor,
p.MyVendorId,
v.Option1,
v.Option2,
v.Option3,
p.VariantOption1Label,
p.VariantOption2Label,
p.VariantOption3Label
};
var orders = await _context.Orders
.Where(o => o.UserId == user.Id)
.OrderByDescending(o => o.Id)
.Skip(perPage * (pageNumber - 1)).Take(perPage)
.GroupJoin(lineItemAndVariant, o => o.Id, l => l.OrderId,
(o, lineItems) => new
{
o.Id,
o.EcomPlatformOrderId,
o.CustomerEmail,
o.FirstName,
o.LastName,
o.Address1,
o.Address2,
o.City,
o.Company,
o.Country,
o.Currency,
o.OrderNumber,
o.Phone,
o.Province,
o.TotalPrice,
o.UserId,
o.Zip,
o.CreatedAt,
LineItems = lineItems
})
.AsNoTracking().ToListAsync();
return orders;
}

Entity Framework - Count distinct books pr. tag using navigation property

I have a table "Book" with a many-to-many relationship to "Tag" and need a distinct Book-count pr. Tag. In SQL, the query looks like this:
SELECT t.NAME,
count(DISTINCT b.BookId)
FROM _Tag t
JOIN Book.BookTag bt
ON t.Id = bt.TagId
JOIN Books b
ON b.BookId = bt.BookId
GROUP BY t.NAME
ORDER BY count(DISTINCT b.BookId) DESC;
I have fetched the tags and included the Books navigation-property and from this I should be able to get distinct BookId's pr. tagname. I want to get the result in a tuple.
So far I have tried the following:
var tagTuples = from tag in tags
join book in tags.Select(t => t.Books) on tag.Books equals book
group new {tag, book} by tag.Name
into g
select new Tuple<string, string, int>("tags", g.Key, g.Select(x => x.book).Count());
...and...
var tagTuples = tags.GroupBy(t => t.Name)
.Select(t2 => new Tuple<string, string, int>("tags", t2.Key, t2.Sum(t4 => t4.Books
.Select(b => b.BookId).Distinct().Count())))
.Where(t3 => !string.IsNullOrWhiteSpace(t3.Item2)).Take(15);
...and my latest version:
var tagTuples =
tags.Select(t => new {t.Name, BookId = t.Books.Select(b => b.BookId)})
.GroupBy(tb => tb.Name)
.Select(tb2 => new Tuple<string, string, int>("tags", tb2.Key, tb2.Sum(tb3 => tb3.BookId.Distinct().Count())));
Nevermind the small differences in the query's - I'm only interested in a solution to the problem described above.
Frustration! It takes me 2 minutes to write an SQL query that does this and I'm pretty sure there's a simple answer, but I lack EF routine.
Thankyou for your time. :)
using(var ctx = new EntitiesContext())
{
// GROUP By name
var bookCountByTag = ctx.Tags.GroupBy(t => t.Name)
.Select(t2 => new {
// SELECT the key (tag name)
t2.Key,
// "GroupBy" has many result, so use SelectMany
Count = t2.SelectMany(t3 => t3.book)
.Distinct()
.Count()})
.ToList();
}

How to avoid "select n+1" pattern in Linq

I have a query (including LinqKit) of the form:
Expression<Func<Country, DateTime, bool>> countryIndepBeforeExpr =
(ct, dt) => ct.IndependenceDate <= dt;
DateTime someDate = GetSomeDate();
var q = db.Continent.AsExpandable().Select(c =>
new
{
c.ID,
c.Name,
c.Area,
Countries = c.Countries.AsQueryable()
.Where(ct => countryIndepBeforeExpr.Invoke(ct, someDate))
.Select(ct => new {ct.ID, ct.Name, ct.IndependenceDate})
});
Now I want to iterate through q... but since the Countries property of each element is of type IQueryable, it will be lazy loaded, causing n+1 queries to be executed, which isn't very nice.
What is the correct way to write this query so that all necessary data will be fetched in a single query to the db?
EDIT
Hm, well it might have helped if I had actually run a Sql trace before asking this question. I assumed that because the inner property was of type IQueryable that it would be lazy-loaded... but after doing some actual testing, it turns out that Linq to Entities is smart enough to run the whole query at once.
Sorry to waste all your time. I would delete the question, but since it already has answers, I can't. Maybe it can serve as some kind of warning to others to test your hypothesis before assuming it to be true!
Include countries to your model when you call for continents. With something like this:
var continents = db.Continent.Include(c => c.Countries).ToArray();
Then you can make your linq operations without iQueryable object.
I think this should work (moving AsExpandable() to root of IQueryable):
var q = db.Continent
.AsExpandable()
.Select(c => new
{
c.ID,
c.Name,
c.Area,
Countries = c.Countries
.Where(ct => countryIndepBeforeExpr.Invoke(ct, someDate))
.Select(ct => new {ct.ID, ct.Name, ct.IndependenceDate})
});
If not, create two IQueryable and join them together:
var continents = db.Continents;
var countries = db.Countries
.AsExpandable()
.Where(c => countryIndepBeforeExpr.Invoke(c, someDate))
.Select(c => new { c.ID, c.Name, c.IndependenceDate });
var q = continents.GroupJoin(countries,
continent => continent.ID,
country => country.ContinentId,
(continent, countries) => new
{
continent.ID,
continent.Name,
continent.Area,
Countries = countries.Select(c => new
{
c.ID,
c.Name,
c.IndependenceDate
})
});

Categories