I'm trying to write a query that contains multiple left joins in linq in a c# .netcore 2.2 application. I've tried writing the query in linq but it is not properly retrieving all the rows. Query I'm trying to convert is as follows.
select ISNULL(b.Id, '00000000-0000-0000-0000-000000000000') as 'Bat Id', p.Id as 'ProductId', p.RP, u.UnitName as 'UnitName', ISNULL(b.QTY,0) as 'BusQty', p.[Name] as 'Product Name'
from Products p left join Bat b
ON p.Id = b.ProductId
left join Units u on p.UOId = u.Id;
linq I have so far
var allProducts = (from p in _db.Products
join s in _db.Bat on p.Id equals s.ProductId into ps
from s in ps.DefaultIfEmpty()
join u in _db.Units on p.UOId equals u.Id
select new
{
BatId = s.Id == null ? Guid.NewGuid() : s.Id,
RP = p.RP,
BusQty = s.QTY == null ? 0 : s.QTY,
ProductName = p.Name,
UnitName = u.UnitName,
ProductId = p.Id,
}).ToList();
You are missing DefaultIfEmpty() on Units, thereby turning it into an inner join
var allProducts = (
from p in _db.Products
join s in _db.Bat on p.Id equals s.ProductId into ps
from s in ps.DefaultIfEmpty()
join u in _db.Units on p.UOId equals u.Id into us
from u in us.DefaultIfEmpty()
select new
{
BatId = s.Id ?? Guid.NewGuid(),
RP = p.RP,
BusQty = s.QTY ?? 0,
ProductName = p.Name,
UnitName = u.UnitName,
ProductId = p.Id,
}).ToList();
Related
I have the following query that gives me expected results in SQL Server Management Studio:
SELECT
u.DisplayName,
up.ColorPreferences,
SUM(rt.Score) AS Points,
COUNT(*) AS Plans,
MAX(pl.Created) AS MaxDate
FROM
[dbo].[Users] u
INNER JOIN
[dbo].[PlanLogs] pl ON u.Id = pl.UserId
INNER JOIN
[dbo].[ResourceTypes] rt ON pl.ResourceTypeId = rt.Id
INNER JOIN
[dbo].[UserProfile] up ON pl.UserId = up.UserId
GROUP BY
u.DisplayName, up.ColorPreferences;
an I have the following working linq query:
from u in _context.Users
join pl in _context.PlanLogs on u.Id equals pl.UserId
join rt in _context.ResourceTypes on pl.ResourceTypeId equals rt.ID
join up in _context.UserProfile on pl.UserId equals up.UserId
group rt by new { u.DisplayName, up.ColorPreferences} into g
select new
{
DisplayName = g.Key.DisplayName,
ColorPrefs = g.Key.ColorPreferences,
Points = g.Sum(x => x.Score),
Plans = g.Count()
};
As you can see, it is missing MaxDate. I can't get access to MaxDate because g contains properties from rt. I've tried the following and i get "Value does not fall within the expected range"
from u in _context.Users
join pl in _context.PlanLogs on u.Id equals pl.UserId
join rt in _context.ResourceTypes on pl.ResourceTypeId equals rt.ID
join up in _context.UserProfile on pl.UserId equals up.UserId
group new { rt, pl } by new { u.DisplayName, up.ColorPreferences} into g
select new
{
DisplayName = g.Key.DisplayName,
ColorPrefs = g.Key.ColorPreferences,
Points = g.Sum(x => x.rt.Score),
Plans = g.Count()
MaxDate = g.Max(m => m.pl.Created)
};
How do i add MaxDate to the results?
Thanks
Have you tried accessing the max value from pl.created on your first linq query? why are you grouping by rt and not the whole result? try this instead :
from u in _context.Users
join pl in _context.PlanLogs on u.Id equals pl.UserId
join rt in _context.ResourceTypes on pl.ResourceTypeId equals rt.ID
join up in _context.UserProfile on pl.UserId equals up.UserId
group u by new { u.DisplayName, up.ColorPreferences} into g
select new
{
DisplayName = g.Key.DisplayName,
ColorPrefs = g.Key.ColorPreferences,
Points = g.Sum(x => x.Score),
Plans = g.Count(),
MaxDate = g.Max(m => m.pl.Created)
};
I solevd this in the end. I needed to pass the specific columns to the group not the whole table:
group new { rt.Score, pl.Created } by..
rather than
group new { rt, pl } by...
Working query:
from u in _context.Users
join pl in _context.PlanLogs on u.Id equals pl.UserId
join rt in _context.ResourceTypes on pl.ResourceTypeId equals rt.ID
join up in _context.UserProfile on pl.UserId equals up.UserId
group new { rt.Score, pl.Created } by new { u.DisplayName, up.ColorPreferences } into g
select new
{
DisplayName = g.Key.DisplayName,
ColorPrefs = g.Key.ColorPreferences,
Points = g.Sum(i => i.Score),
Plans = g.Count(),
MaxCreated = g.Max(i => i.Created).ToString("dd/MM/yyyy HH:mm")
}
I try to translate this SQL code :
SELECT w.Id, w.LastName, w.FirstName, SUM(d.Price*dt.Number) AS somme
FROM Waiter w
INNER JOIN Client c on w.Id = c.WaiterId
INNER JOIN DisheOnTable dt on c.Id = dt.ClientId
INNER JOIN Dishe d on dt.DisheId = d.Id
GROUP BY w.Id, w.LastName, w.FirstName
ORDER BY somme DESC;
in entity framework.
I tried something like this
var query2 = (from w in db.Waiter
join c in db.Client on w.Id equals c.WaiterId
join dt in db.DisheOnTable on c.Id equals dt.ClientId
join d in db.Dishe on dt.DisheId equals d.Id
group w by new { w.Id, w.LastName, w.FirstName } into g
//orderby g.Select() descending
select new
{
id = g.Key.Id,
lastname = g.Key.LastName,
firstname = g.Key.FirstName,
total = g.Sum(q => q.)
});
but my sum doesn't work (after multiple research and try) and i don't know how to multiply my variables.
PS : The SQL statement works well, i tried it.
Thank you for helping guys ! :)
You need to group on both dish and DishOnTable alias as Price is in Dish and Number is in DishOnTable:
group new{ d,dt} by new {w.Id, w.LastName, w.FirstName} into g
and now sum the columns which you want from it
select new {
id = g.Key.Id,
lastname = g.Key.LastName,
firstname = g.Key.FirstName,
total = g.Sum(q => q.d.Price * q.dt.Number)
}).OrderBy(x=>x.total)
I'm working with the following linq query:
var docList = from c in container.DocumentDeliveryPreferences
join o in container.Documents on c.DocumentId equals o.DocumentId
select new { o.Name, o.DocumentType, c.CustomerId };
How can I modify this to select only Documents where c.CustomerId equals X(some paramenter)?
You could try something the following:
var docList = from c in container.DocumentDeliveryPreferences
join o in container.Documents
on c.DocumentId equals o.DocumentId
where c.CustomerId == X
select new { o.Name, o.DocumentType, c.CustomerId };
where X is your parameter.
I have written the below given query in SQL server 2008:
(SELECT p.postid,
p.title,
p.disabled,
l.locationname
FROM posts p
INNER JOIN categories c
ON p.categoryid = c.categoryid
INNER JOIN users u
ON p.userid = u.userid
INNER JOIN tags t
ON p.tagid = t.tagid
INNER JOIN locations l
ON p.locationid = l.locationid
LEFT JOIN postimages pm
ON p.postid = pm.postid
WHERE p.categoryid = 1
GROUP BY p.postid,
p.title,
p.disabled,
l.locationname)
ORDER BY p.postid DESC
I want to write the above query in LINQ.
I tried a little and able to write the query below:
var objPosts = (from p in _dbcontext.Posts
join us in _dbcontext.Users on p.UserId equals us.UserId
join tag in _dbcontext.Tags on p.TagId equals tag.TagId
join cat in _dbcontext.Categories on p.CategoryId equals cat.CategoryId
join loc in _dbcontext.Locations on p.LocationId equals loc.LocationId
join img in _dbcontext.PostImages on p.PostId equals img.PostId into gj
from postimg in gj.DefaultIfEmpty()
where p.Disabled == false && p.CategoryId == userPost.CategoryId || p.UserId == userPost.UserId || p.TagId == userPost.TagId || p.LocationId == userPost.LocationId
orderby p.PostId descending
select new
{
PostId = p.PostId,
PostTitle = p.Title,
//ImageInfo = postimg.ImagePath,
//ThumbNailInfo = p.ThubNailInfo,
PostShortDescription = p.ShortDescription,
UserId = us.UserId,
UserName = us.Name,
TagId = tag.TagId,
TagTitle = tag.Title,
CategoryId = cat.CategoryId,
CategoryName = cat.CategoryName,
LocationId = loc.LocationId,
LocationName = loc.LocationName
});
I am unable to apply the group by logic in LINQ. Can anyone please convert my SQL to LINQ. Thanks
group new { p, l } by new
{
p.postid,
p.title,
p.disabled,
l.locationname
} into g
orderby g.Key.PostId descending
select new
{
g.key.postid,
g.key.title,
g.key.disabled,
g.key.locationname
}
The missing part in your query is that you are not selecting anything...
You got the joins ok, left outer join ok, predicates (where), ordering, but no projection, and no group by.
Below should get you started:
group p by p.PostId into pg
select new {Post=p, Location=loc};
This would return return a collection of new objects whose properties Post and Location.
I'm trying convert this SQL to Entity Framework LINQ, but don't working.
My SQL code:
SELECT
s.Id,
s.OriginalPhotoBlobId,
s.PhotoBlobExtension,
ISNULL(s.ProductSkuKey, p.[Key]) as [Key],
p.Name,
ISNULL(sp.Price, 0) as [Price],
sp.PriceList_Id
FROM SKUs s
INNER JOIN Products p on p.Id = s.Product_Id
LEFT JOIN SKUPrices sp on sp.SKU_Id = s.Id
My Entity Framework Code:
var db = this.Context;
var prices = from s in db.SKUs
join p in db.Products on s.Product equals p
join sp in db.SKUPrices on s equals sp.SKU into gj
from spss in gj.DefaultIfEmpty()
select new PriceListItem
{
Id = s.Id,
BlobId = s.OriginalPhotoBlobId,
BlobExtension = s.PhotoBlobExtension,
Key = ((s.ProductSkuKey == null || s.ProductSkuKey.Trim() == string.Empty) ? p.Key : s.ProductSkuKey),
Name = p.Name,
Price = (spss == null ? default(double) : spss.Price),
};
I think you should use navigation properties. Navigation properties are used to navigate through relations in data.
try joining the properties not the classes
var prices = from s in db.SKUs
join p in db.Products on s.Product_Id equals p.Id
join sp in db.SKUPrices on sp.SKU_Id = s.Id into gj
from sp in gj.DefaultIfEmpty()
select new PriceListItem
{
Id = s.Id,
BlobId = s.OriginalPhotoBlobId,
BlobExtension = s.PhotoBlobExtension,
Key = ((s.ProductSkuKey == null || s.ProductSkuKey.Trim() == string.Empty) ? p.Key : s.ProductSkuKey),
Name = p.Name,
Price = (sp == null ? default(double) : sp .Price),
};