I have a SQL Query and would like to convert into LINQ Method Syntax (Lambda) but it seems that I am stuck at the multiple group join and it confuses me.
Below is the SQL that I wanted to change into LINQ
select MerchantUserId, usex.Nickname, MAX(OrderTransaction.CreatedDate) as LastOrderDate, sd.Url, st.Name as storename
from OrderTransaction
left join UserExtend usex
on usex.Id = OrderTransaction.MerchantUserId
left join StoreDomain sd
on sd.StoreId = usex.StoreId
left join store st
on st.id = sd.StoreId
where OrderTransaction.Status <> 8
and sd.IsPrimary = 1
group by MerchantUserId,usex.Nickname,sd.Url,st.Name
order by LastOrderDate desc
Below is the query that I tried to link all three tables together. Am I doing it correctly in terms of linking 3 tables together?
var list = _ApplicationDbContext.UserExtend
.GroupJoin(_ApplicationDbContext.OrderTransaction, usex => usex.Id, ord => ord.MerchantUserId, (usex, ord) => new { usex, ord})
.GroupJoin(_ApplicationDbContext.StoreDomain, usexOrd => usexOrd.usex.StoreId, sd => sd.StoreId, (usexOrdStoreDom, sd) => new { usexOrdStoreDom , sd})
.GroupJoin(_ApplicationDbContext.Store, usexOrdStoreDom => usexOrdStoreDom.usexOrdStoreDom.usex.StoreId, st => st.Id, (usexOrdStoreDomStore , st ) => new { usexOrdStoreDomStore, st })
The equivalent of your SQL query is the following link phrase.
The GroupJoin is for when you want to match a value with several values.
For more information, you can refer to this link: Linq to Entities join vs groupjoin
var list = _ApplicationDbContext.UserExtend.Join(_ApplicationDbContext.OrderTransaction,
usex => usex.Id,
ord => ord.MerchantUserId,
(usex, ord) => new { usex, ord })
.Join(_ApplicationDbContext.StoreDomain,
usexOrd => usexOrd.usex.StoreId,
sd => sd.StoreId,
(usexOrd, sd) => new { usexOrd, sd })
.Join(_ApplicationDbContext.Store,
usexOrdStoreDom => usexOrdStoreDom.sd.StoreId,
st => st.Id,
(usexOrdStoreDom, st) => new { usexOrdStoreDom, st })
.GroupBy(a => new { a.usexOrdStoreDom.usexOrd.ord.MerchantUserId, a.usexOrdStoreDom.usexOrd.usex.Nickname, a.usexOrdStoreDom.sd.Url, a.st.Name, a.usexOrdStoreDom.usexOrd.ord.CreatedDate })
.OrderBy(a => a.Key.CreatedDate)
.Select(a => new
{
MerchantUserId = a.Key.MerchantUserId,
Nickname = a.Key.Nickname,
Url = a.Key.Url,
storename = a.Key.Name,
LastOrderDate = a.Max(x => x.usexOrdStoreDom.usexOrd.ord.CreatedDate)
})
.ToList();
Related
I have a problem to write in lambda query this sql query:
select c.Id, c.Name, c.SomeNumber, count(*) from TableA a
inner join TableB b
on a.Id = b.aId
inner join TableC c
on c.BId = b.Id
where b.Status = N'Approved'
and c.Scope = N'Scope1'
group by a.Id, a.Name, a.SomeNumber
Can you guys help me with this one ? I want to write lambda query to execute this in code. I'm using EF Core 3.1
This is what I ended up so far:
var query = await _dbContext.TableA.Where(a => a.TableB.Any(b => b.Status.Equals("Approved")
&& b.TableC.Any(c => c.Scope.Equals("Scope1"))))
.GroupBy(g => new { Id = g.Id, Name = g.Name, SomeNumber = g.SomeNumber })
.Select(s => new { Id = s.Key.Id, Name = s.Key.Name, SomeNumber = s.Key.SomeNumber, Count = s.Count() })
.GroupBy(g => g.Id).Select(s => new {Id = s.Key, Count = s.Count()}).ToListAsync();
Well, this is corrected query. I have used Query syntax which is more readable when query has lot of joins or SelectMany.
var query =
from a in _dbContext.TableA
from b in a.TableB
from c in b.TableC
where b.Status == "Approved" && c.Scope == "Scope1"
group a by new { a.Id, a.Name, a.SomeNumber } into g
select new
{
g.Key.Id,
g.Key.Name,
g.Key.SomeNumber,
Count = g.Count()
}
var result = await query.ToListAsync();
It's maybe easier to start from the many end and work up through the navigation properties
tableC
.Where(c => c.Scope == "Scope1" && c.BEntity.Status == "Approved")
.GroupBy(c => new
{
c.BEntity.AEntity.Id,
c.BEntity.AEntity.Name,
c.BEntity.AEntity.SomeNumber
})
.Select(g => new { g.Key.Id, g.Key.Name, g.Key.SomeNumber, Ct = g.Count()})
EF knows how to do joins when you navigate around the object tree in the where. By starting at the many and and working up to the 1 end of the relationship it means you don't have to get complex with asking "do any of the children of this parent have a status of ..."
This is my SQL query:
select
m.Name, s.Time, t.TheaterNumber
from
Movies m
join
MovieSeanceTheaters mst on mst.MovieId = m.MovieID
join
Theaters t on t.ID = mst.TheaterId
join
Seances s on mst.SeanceId = s.ID
This is my attempt at a Linq query:
var result = (from m in _context.Movies
join mst in _context.MovieSeanceTheaters on m.ID equals mst.MovieId
join t in _context.Theaters on mst.TheaterId equals t.ID
join s in _context.Seances on mst.TheaterId equals s.ID
select new { Film = m.Name, Salon = t.Name, Seans = s.Time }
).ToList();
I made this attempt, but I want to make with lambda for instance:
var result = movieManager.GetAll().Where(x => x.MovieSeanceTheaters)....
I couldn't do that.
If I understand you correctly, you want to rewrite your query from query syntax to method syntax?
Here we are!
var result = _context.Movies
.Join(_context.MovieSeanceTheaters,
m => m.MovieID,
mst => mst.MovieID,
(m, mst) => new
{
m = m,
mst = mst
})
.Join(_context.Theaters,
temp0 => temp0.mst.TheaterID,
t => t.ID,
(temp0, t) =>
new
{
temp0 = temp0,
t = t
})
.Join(_context.Seances,
temp1 => temp1.temp0.mst.TheaterID,
s => s.ID,
(temp1, s) =>
new
{
Film = temp1.temp0.m.Name,
Salon = temp1.t.TheaterNumber,
Seans = s.Time
});
Looks ugly, doesn't it?
Most often, the method syntax is more compact and convenient. But in this case, leave it as is.
i have this inherited SQL view code that I converted to linq to get some data out in the meantime, in LINQPad it works as expected, but upon transferring it to my c# solution, the subcollections are not loaded.
var query = from poh in _pckOrderHeadeRepository.GetAllIncluding(pd => pd.PckOrderDetail)
join mcs in _mstrConsigneeShipToRepository.GetAll() on poh.RouteId equals mcs.Consignee
//select new {poh, mcs}; //works
join det in (
from d in _pckOrderDetailRepository.GetAllIncluding(pd=> pd.PckOrderHeader, pd => pd.MstrSku)
join s in (
from shpCartonHeader in _shpCartonHeaderRepository.GetAll()
group shpCartonHeader by new
{
shpCartonHeader.OrderNum
}
into g
select new
{
g.Key.OrderNum,
CartonWeight = g.Sum(p => p.TotalWeight)
}) on d.PckOrderHeader.OrderNum equals s.OrderNum into sJoin
from s in sJoin.DefaultIfEmpty()
group new {d.PckOrderHeader, d, d.MstrSku, s} by new
{
d.PckOrderHeader.OrderNum
}
into g
select new
{
g.Key.OrderNum,
OrderQty = g.Sum(p => p.d.OrderQty),
OrderWeightOpen = (decimal?)g.Where(p => p.d.PckOrderHeader.OrderStat.Equals("OPEN")).Sum(p => p.d.MstrSku.Weight * p.d.OrderQty),
OrderWeightReleased = (decimal?)g.Where(p => p.d.PckOrderHeader.OrderStat.Equals("RELEASED")).Sum(p => p.d.MstrSku.Weight * p.d.PickingQty + p.s.CartonWeight),
OrderWeightPacked = (decimal?)g.Where(p => p.d.PckOrderHeader.OrderStat.Equals("PACKED")).Sum(p => p.s.CartonWeight),
PrePack = g.Max(p => p.d.MstrSku.Prepack)
}) on poh.OrderNum equals det.OrderNum
join toa in _shpTrailerOrderAssignmentRepository.GetAll() on poh.OrderNum equals toa.OrderNum into
toaJoin
from toa in toaJoin.DefaultIfEmpty()
select new
{
det,
poh,
toa,
mcs
};
this part in particular:
select new
{
g.Key.OrderNum,
OrderQty = g.Sum(p => p.d.OrderQty),
OrderWeightOpen = (decimal?)g.Where(p => p.d.PckOrderHeader.OrderStat.Equals("OPEN")).Sum(p => p.d.MstrSku.Weight * p.d.OrderQty),
OrderWeightReleased = (decimal?)g.Where(p => p.d.PckOrderHeader.OrderStat.Equals("RELEASED")).Sum(p => p.d.MstrSku.Weight * p.d.PickingQty + p.s.CartonWeight),
OrderWeightPacked = (decimal?)g.Where(p => p.d.PckOrderHeader.OrderStat.Equals("PACKED")).Sum(p => p.s.CartonWeight),
PrePack = g.Max(p => p.d.MstrSku.Prepack)
}) on poh.OrderNum equals det.OrderNum
for example this:
PrePack = g.Max(p => p.d.MstrSku.Prepack) // MstrSku is not loaded
and the property inside p.d (PckOrderDetail)
public virtual MstrSku MstrSku { get; set; }
the equivalent query in linqpad works correctly, so im wondering what am I missing to properly load the sub properties to mimic LINQPads behaviour.
if you want to use p.d.MstrSku.Prepack then you have to include it in the outer table. when you include it in joined table you cannot select.
use it in the first line like the sample below
.Include(x => x.OrderDetails.Select(y => y.MstrSku)).ToList();
I would like if someone helps me to convert this SQL Query to LINQ syntax.
SELECT i.Id, i.Condomino as Condomino, i.Interno as Interno,
p.NomePiano as NomePiano, s.Nome as NomeCondominio,
m.millesimi_fabbisogno_acs, m.millesimi_fabbisogno_riscaldamento
FROM Interni i
INNER JOIN Piani p ON i.IdPiano = p.Id
INNER JOIN Stabili s ON i.IdStabile = s.Id
LEFT JOIN MillesimiTabellaC m ON i.Id = m.idInterno
WHERE s.IdCondominio = {0}
I tried using something like this, but is not working..
return _Db.Interni.Include("Piani").Where(x => x.Piani.IdCondominio == iidcond).ToList();
I made it on-the-spot (so it's not tested), but perhaps it's enough to give you the idea. I'm also assuming that your DB model has foreign keys set up.
var result = _db.Interni
.Where(i => i.Stabili.IdCondominio = [value])
.Select(i => new
{
i.Id,
Condomino = i.Condomino,
Interno = i.Interno,
NomePiano = i.Piani.NomePiano,
NomeCondominio = i.Stabili.Nome,
i.MillesimiTabellaC.millesimi_fabbisogno_acs,
i.MillesimiTabellaC.millesimi_fabbisogno_riscaldamento
})
.ToList();
update
In case you don't have a foreign key between Interni and MillesimiTabellaC, try this:
var result = _db.Interni
.Include(i => i.Piani)
.Include(i => i.Stabili)
.Where(i => i.Stabili.IdCondominio = [value])
.Select(i => new
{
Interni = i,
MillesimiTabellaC = _db.MillesimiTabellaC.Where(m => i.Id = m.idInterno)
})
.Select(x => new
{
Id = x.Interni.Id,
Condomino = x.Interni.Condomino,
Interno = x.Interni.Interno,
NomePiano = x.Interni.Piani.NomePiano,
NomeCondominio = x.Interni.Stabili.Nome,
x.MillesimiTabellaC?.millesimi_fabbisogno_acs,
x.MillesimiTabellaC?.millesimi_fabbisogno_riscaldamento
})
.ToList();
I have an SQL expression
select S.SpecialtyName, COUNT(distinct SUC.SiteUserId) as Subscribers
from SiteUserContent SUC Inner join
Specialties S on SUC.SpecialtyId = S.SpecialtyId Inner join
SiteUser SU on SUC.SiteUserId = SU.SiteUserId
where SU.DeletedFlag = 0
group by S.SpecialtyName
Order by S.SpecialtyName
What will be the corresponding LINQ expression for the same?
from suc in context.SiteUserContent
join s in context.Specialties on suc.SpecialtyId equals s.SpecialtyId
join su in context.SiteUser on suc.SiteUserId equals su.SiteUserId
where su.DeletedFlag == 0
select new { suc.SiteUserId, s.SpecialityName } into x
group x by x.SpecialityName into g
orderby g.Key
select new {
SpecialityName = g.Key,
Subscribers = g.Select(i => i.SiteUserId).Distinct().Count()
}
Generated SQL will not be same, but I think result of query execution should be same.
var results = contex.SiteUserContent
.Join(context.Specialties, suc => suc.SpecialtyId, s => s.SpecialtyId, (suc, s) => new { suc, s })
.Join(context.SiteUser, i = i.suc.SiteUserId, su => su.SiteUserId, (i, su) => new { suc = i.suc, s = i.s, su = su })
.Where(i => i.su.DeletedFlag == 0)
.GroupBy(i => i.s.SpecialtyName)
.Select(g => new {
SpecialityName = g.Key,
Subscribers = g.Select(i => i.suc.SiteUserId)
.Distinct()
.Count()
})
.OrderBy(i => i.SpecialityName);