SQL query in LINQ to SQL - c#

I am trying to write SQL query in LINQ to SQL but after 4h of trying i gave up.
select B.* from Bid B
join
(
select BidId, max(BidVersion) as maxVersion
from Bid
group by BidId
) X on B.BidId = X.BidId and B.BidVersion = X.maxVersion
i saw some tips on the stackOverflow but they werent helpful.
I am using some VERY bad code like:
List<Bid> bidEntities = new List<Bid>();
var newest = from bid in _dbContext.Bids
group bid by bid.BidId into groups
select new { Id = groups.Key, Vs = groups.Max(b => b.BidVersion) };
foreach (var group in newest)
{
bidEntities.Add(await _dbContext.Bids.Where(b => b.BidId == group.Id && b.BidVersion == group.Vs).SingleOrDefaultAsync());
}
Thank you for any advice.

Something like this should work:
var rows = Bids
.GroupBy(b => b.BidId)
.Select(g => g.OrderByDescending(gg => gg.BidVersion).FirstOrDefault())
With LINQ, it helps sometimes not to think in the 'SQL way', but about what you really want. You want the highest version bid for each BidId

Related

Join 2 table and group 2 field in linq

I have a very simple SQL
SELECT s.shop_code
,SUM(im.amt) sum_amt
,s.cell_no#1 shop_cell
FROM tb_sn_so_wt_mst im
,tb_cm_shop_inf s
WHERE im.shop_code = s.shop_code
GROUP BY s.shop_code, s.cell_no#1)
then i try to code linq
var listResult = from warrantyMaster in listWarrantyMasters2.Records
join shopInfo in listShopInfos
on warrantyMaster.ShopCode equals shopInfo.ShopCode
i don't know group by shop code and cell no and sum atm, any one help me out of this problem
The group by syntax with some examples is explained here group clause (C# Reference) and related links.
Here is the direct translation of your SQL query (of course the field names are just my guess since you didn't provide your classes):
var query = from im in listWarrantyMasters2.Records
join s in listShopInfos
on im.ShopCode equals s.ShopCode
group im by new { s.ShopCode, s.CellNo } into g
select new
{
g.Key.ShopCode,
g.Key.CellNo,
SumAmt = g.Sum(e => e.Amt)
};
You can try this code:
var results = from warrantyMaster in listWarrantyMasters2.Records
from shopInfo in listShopInfos
.Where(mapping => mapping.ShopCode == warrantyMaster.ShopCode )
.select new
{
ShopCode = warrantyMaster.ShopCode,
ATM = listWarrantyMasters2.ATM,
ShellNo = shopInfo.ShellNo
}
.GroupBy(x=> new { x.ShopCode, x.ShellNo })
.Select(x=>
new{
ShopCode = x.Key.ShopCode,
ShellNo = x.Key.ShellNo,
SumATM = x.Sum(item=>item.ATM)
});

convert SQL query to Linq

Could somebody assist me in converting a sql query into LINQ ? I well understand SQL queries, but I am a novice in Linq. Thank you so much for help me.
SELECT
subConsulta."NitIps",
subConsulta."NumFactura",
COUNT(*)
FROM
(SELECT
DISTINCT acf."NitIps",
acf."NumFactura",
acf."TipoSoporte"
FROM
"t_ArchivoCentralFacturacion" AS acf
inner join "t_TRCompartaTiposDocumentalesAC" AS ctd
on
acf."TipoSoporte"= ctd."Id"
GROUP BY
acf."NitIps",
acf."NumFactura",
acf."TipoSoporte")as subConsulta
GROUP BY
subConsulta."NitIps",
subConsulta."NumFactura"
ORDER BY
subConsulta."NitIps",
subConsulta."NumFactura"
If you map your tables to entities it looks like follow:
var first = from archivoCentralFacturacion in ArchivoCentralFacturacions
group archivoCentralFacturacion by new {
c.NitIps,
c.NumFactura,
c.TipoSoporte
} into subConsulta
select subConsulta;
var result = (from f in first
group f by new {
f.NitIps,
f.NumFactura
} into r
select new {
NitIps = r.NitIps,
NumFactura = r.NumFactura,
ResultCount = r.Count()
}).OrderBy(x => x.NitIps).ThenBy(x => x.NumFactura);

Converting SQL to LINQ query when I cannot use "IN"

I'm trying to convert this very simple piece of SQL to LINQ:
select * from Projects p
inner join Documents d
on p.ProjectID = d.ProjectID
left join Revisions r
on r.DocumentID = d.DocumentID
and r.RevisionID IN (SELECT max(r2.RevisionID) FROM Revisions r2 GROUP BY r2.DocumentID)
WHERE p.ProjectID = 21 -- Query string in code
This says, if any revisions exist for a document, return me the highest revision ID. As it's a left join, if not revisions exist, I still want the results returned.
This works as expected, any revisions which exist are shown (and the highest revision ID is returned) and so are all documents without any revisions.
When trying to write this using LINQ, I only get results where revisions exist for a document.
Here is my attempt so far:
var query = from p in db.Projects
join d in db.Documents on new { ProjectID = p.ProjectID } equals new { ProjectID = Convert.ToInt32(d.ProjectID) }
join r in db.Revisions on new { DocumentID = d.DocumentID } equals new { DocumentID = Convert.ToInt32(r.DocumentID) } into r_join
from r in r_join.DefaultIfEmpty()
where
(from r2 in db.Revisions
group r2 by new { r2.DocumentID }
into g
select new { MaxRevisionID = g.Max(x => x.RevisionID) }).Contains(
new { MaxRevisionID = r.RevisionID }) &&
p.ProjectID == Convert.ToInt32(Request.QueryString["projectId"])
select new { d.DocumentID, d.DocumentNumber, d.DocumentTitle, RevisionNumber = r.RevisionNumber ?? "<No rev>", Status = r.DocumentStatuse == null ? "<Not set>" : r.DocumentStatuse.Status };
I'm not very good at LINQ and have been using the converter "Linqer" to help me out, but when trying I get the following message:
"SQL cannot be converted to LINQ: Only "=" operator in JOIN expression
can be used. "IN" operator cannot be converted."
You'll see I have .DefaultIfEmpty() on the revisions table. If I remove the where ( piece of code which does the grouping, I get the desired results whether or not a revision exists for a document or not. But the where clause should return the highest revision number for a document IF there is a link, if not I still want to return all the other data. Unlike my SQL code, this doesn't happen. It only ever returns me data where there is a link to the revisions table.
I hope that makes a little bit of sense. The group by code is what is messing up my result set. Regardless if there is a link to the revisions table, I still want my results returned. Please help!
Thanks.
=======
The code I am now using thanks to Gert.
var query = from p in db.Projects
from d in p.Documents
where p.ProjectID == Convert.ToInt32(Request.QueryString["projectId"])
select new
{
p.ProjectID,
d.DocumentNumber,
d.DocumentID,
d.DocumentTitle,
Status = d.Revisions
.OrderByDescending(rn => rn.RevisionID)
.FirstOrDefault().DocumentStatuse.Status,
RevisionNumber = d.Revisions
.OrderByDescending(rn => rn.RevisionID)
.FirstOrDefault().RevisionNumber
};
gvDocumentSelection.DataSource = query;
gvDocumentSelection.DataBind();
Although this works, you'll see I'm selecting two fields from the revisions table by running the same code, but selecting two different fields. I'm guessing there is a better, more efficient way to do this? Ideally I would like to join on the revisions table in case I need to access more fields, but then I'm left with the same grouping problem again.
Status = d.Revisions
.OrderByDescending(rn => rn.RevisionID)
.FirstOrDefault().DocumentStatuse.Status,
RevisionNumber = d.Revisions
.OrderByDescending(rn => rn.RevisionID)
.FirstOrDefault().RevisionNumber
Final working code:
var query = from p in db.Projects
from d in p.Documents
where p.ProjectID == Convert.ToInt32(Request.QueryString["projectId"])
select new
{
p.ProjectID,
d.DocumentNumber,
d.DocumentID,
d.DocumentTitle,
LastRevision = d.Revisions
.OrderByDescending(rn => rn.RevisionID)
.FirstOrDefault()
};
var results = from x in query
select
new
{
x.ProjectID,
x.DocumentNumber,
x.DocumentID,
x.DocumentTitle,
x.LastRevision.RevisionNumber,
x.LastRevision.DocumentStatuse.Status
};
gvDocumentSelection.DataSource = results;
gvDocumentSelection.DataBind();
If you've got 1:n navigation properties there is a much simpler (and recommended) way to achieve this:
from p in db.Projects
from d in p.Documents
select new { p, d,
LastRevision = d.Revisions
.OrderByDescending(r => r.RevisionId)
.FirstOrDefault() }
Without navigation properties it is similar:
from p in db.Projects
join d in db.Documents on new { ProjectID = p.ProjectID }
equals new { ProjectID = Convert.ToInt32(d.ProjectID) }
select new { p, d,
LastRevision = db.Revisions
.Where(r => d.DocumentID = Convert.ToInt32(r.DocumentID))
.OrderByDescending(r => r.RevisionId)
.FirstOrDefault() }
Edit
You can amend this very wide base query with all kinds of projections, like:
from x in query select new { x.p.ProjectName,
x.d.DocumentName,
x.LastRevision.DocumentStatus.Status,
x.LastRevision.FieldA,
x.LastRevision.FieldB
}

Linq to SQL join and group

I have two tables in my database:
Town:
userid, buildingid
Building:
buildingid, buildingname
What i want is to populate a GridView like this:
But I don't want the buildings to be shown more than once. Here is my code:
var buildings = dc.Towns
.Where(t => t.userid == userid)
.GroupJoin(dc.Buildings,
t => t.buildingid,
b => b.buildingid,
(Towns, Buildings) => new
{
BuildningName = Buildings.First().buildingname,
Count = Towns.Building.Towns.Count()
});
gvBuildings.DataSource = buildings.ToList();
gvBuildings.DataBind();
New code which works:
var buildings = (from t in dc.Towns
where t.userid == userid
join b in dc.Buildings
on t.buildingid equals b.buildingid
into j1
from j2 in j1.DefaultIfEmpty()
group j2 by j2.buildingname
into grouped
select new
{
buildingname = grouped.Key,
Count = grouped.Count()
});
gvBuildings.DataSource = buildings.ToList();
gvBuildings.DataBind();
var buildings = from t in dc.Towns
join b in dc.Buildings on t.buildingid equals b.buildingid into j1
from j2 in j1.DefaultIfEmpty()
group j2 by b.buildingname into grouped
select new { buildingname = grouped.key, Count = grouped.Count()}
I think this should do it. I have not tested it so it might give error but it will be something like this.
Wouldn't something like this do it?
Users
.Select(User => new {User, User.Building})
.GroupBy(x => x.Building)
.Select(g=> new {Building = g.Key, Count = g.Count()})
According to my experience with Linq to SQL, when the expression is becoming complicated it is better to write a stored procedure and call it with Linq to SQL. In this way you get better maintainability and upgradeability.
Rather than an option to pure SQL, I see “Linqu to SQL” as a tool to get hard typed object representation of SQL data sets. Nothing more.
Hope it helps you.

LINQ: adding OrderBy to query

I'm at the finish line for my university project, and I'm kinda stuck at finishing a query.
The working query looks like this:
var Report = from query in Document.Descendants("order")
group query by query.Element("seller").Value
into qGroup
select new Orders
{
Seller = qGroup.Key,
Quantity = qGroup.Sum(p => int.Parse(p.Element("quantity").Value)).ToString()
};
I would really appreciate it if you can show me, how to Order the results by the given "Quantity" in descending order.
Thanks!
var Report = (from query in Document.Descendants("order")
group query by query.Element("seller").Value into qGroup
select new Orders
{
Seller = qGroup.Key,
Quantity = qGroup.Sum(p => int.Parse(p.Element("quantity").Value)).ToString()
})
.OrderByDescending(order => order.Quantity);
Please do this :
var Report = (from query in Document.Descendants("order")
group query by query.Element("seller").Value
into qGroup
select new Orders
{
Seller = qGroup.Key,
Quantity = qGroup.Sum(p => int.Parse(p.Element("quantity").Value)).ToString()
}).OrderByDescending(x => x.Quantity);
HTH !!!!
(Kudos to LINQ Orderby Descending Query )
The answers by Skippy and Andrei work, but you can also write as
var Report = from query in Document.Descendants("order")
group query by query.Element("seller").Value
into qGroup
let qty = qGroup.Sum(p =>int.Parse(p.Element("quantity").Value)).ToString()
orderby qty descending
select new Orders
{
Seller = qGroup.Key,
Quantity = qty
};
if you'd rather keep it all in one syntax.

Categories

Resources