Translate nested select of oracle query to linq - c#

I was given an oracle query and am trying to translate it to linq. I have been successful up to the point of the inner select.
select distinct pm.projNumber, nvl(s.submission_nbr, ppo.submission_nbr) submission_nbr, nvl(ot.objectname, pot.objectname) objectname , wa.assigned, f.lname, f.fname
from wfassignment wa
join CodeTab c on c.codeid = wa.appr_stat
join projobject po on po.objectid = wa.objectid
join projmain pm on pm.projid = po.projid
join hhistory s on s.Prop_no = pm.Prop_No and s.Inst_Code = pm.Inst_Code and pm.System = 'foo' and s.mark = po.mark
left join objecttypes ot on ot.objecttype = po.objecttype and ot.system = pm.system
left join(
select a.mark, a.objecttype, a.submitdate, c.submission_nbr
from projobject a
join b on b.projid = a.projid
join c on c.Prop_no = b.Prop_No and c.Inst_Code = b.Inst_Code and b.System = 'foo' and c.mark = a.mark ) ppo on ppo.mark = s.parentmark
left join objecttypes pot on pot.objecttype = ppo.objecttype and pot.system = pm.system
join faculty f on f.unique_id = wa.unique_id
where wa.completed is null and wa.unique_id in ('foo', 'bar', 'foo', 'bar')
below is my C# code up until "left join (select... )"
var pageObject = (
from wa in db.WFASSIGNMENTs
join c in db.CODETABs on wa.APPR_STAT equals c.CODEID
join po in db.PROJOBJECTs on wa.OBJECTID equals po.OBJECTID
join pm in db.PROJMAINs on po.PROJID equals pm.PROJID
join s in db.HHISTORies on new { pm.PROP_NO, pm.INST_CODE, po.MARK } equals new { s.PROP_NO, s.INST_CODE, s.MARK }
join ot in db.OBJECTTYPES on new { OBJECTTYPE = po.OBJECTTYPE, pm.SYSTEM } equals new { OBJECTTYPE = ot.OBJECTTYPE1, ot.SYSTEM }
How do I translate the inner select to linq?

I pulled out the inner select into another variable and just joined that variable. Did the trick.

Related

How to rewrite sql query to linq

I'm trying to rewrite sql query to linq but can't do it myself.
The most problem for me is to get I,II and III aggregated values.
Sql query:
select o.Name,t.TypeID, SUM(e.I),SUM(e.II),SUM(e.III) from Expenditure e
join Finance f on f.FinanceId = e.FinanceId
join FinanceYear fy on fy.FinanceYearId = f.FinanceYearId and fy.StatusId = 1
join Project p on p.ProjectId = fy.ProjectId
join Organization o on o.OrganizationId = p.OrganizationId
join Type t on t.TypeID = p.TypeID
where fy.Year = 2018
group by o.Name,s.TypeID
and what I have done so far is:
var x = (from e in _db.Expenditures
join f in _db.Finances on e.FinanceId equals f.FinanceId
join fy in _db.FinanceYears on f.FinanceYearId equals fy.FinanceYearId and fy.StatusId = 1 // this does not work, cant join on multiple conditions?
join p in _db.Projects on fy.ProjectId equals p.ProjectId
join o in _db.Organizations on p.OrganizationId equals o.OrganizationId
join s in _db.Types on p.TypeId equals s.TypeId
group new { o, s } by new { o.OrganizationId, s.TypeId }
into grp
select new AggModel
{
OrganizationId = grp.Key.OrganizationId,
TypeId = grp.Key.TypeId,
I = ?,
II = ?,
III = ?,
}
);
Try something like this:
group new { e, o, s } by new { o.OrganizationId, s.TypeId }
into grp
select new AggModel
{
OrganizationId = grp.Key.OrganizationId,
TypeId = grp.Key.TypeId,
I = grp.Sum(a => a.e.I),
II = grp.Sum(a => a.e.II),
III = grp.Sum(a => a.e.III),
}
You'll need to adjust the right side of the lambda to navigate to the correct property.
You Need to use the Group by for aggregation methods.
Check the below link for more Knowledge.
How to use aggregate functions in linq with joins?

Error in SQL query

I'm trying to create a report that displays some information in a DataGrid but I am having a problem with the SQL method. The fields I am displaying are coming from all different tables. When I run the query in MySqlWorkbench it works but when I try run the program in visual studio I get an error.
private static string SearchSQL
{
get
{
return #" SELECT fleetchecklist.*,
cl.ChecklistNo As CheckListNo,
v.VehicleOwnerID AS VehicleOwnerID,
v.VehicleOwner AS VehicleOwnerName,
v.Reg As VehicleReg,
t.TrailerOwnerID AS TrailerOwnerID,
t.TrailerOwner AS TrailerOwnerName,
t.Reg As TrailerReg,
vdlc.Description AS VehicleDriverLicenseClassName,
tdlc.Description AS TrailerDriverLicenseClassName,
m1.MaintenanceNo AS MaintenanceNo,
m1.Date AS Date
FROM fleetchecklist
LEFT JOIN maintenance m1 ON m1.LinkedID
LEFT JOIN Vehicle v ON m1.LinkedID = v.ID
LEFT JOIN Trailer t ON m1.LinkedID = t.ID
left join Employee ve ON v.VehicleOwnerID = ve.ID
LEFT JOIN Employee te ON t.TrailerOwnerID = te.ID
LEFT JOIN driverlicenseclass vdlc ON ve.DriverLicenseClassID = vdlc.ID
LEFT JOIN driverlicenseclass tdlc ON te.DriverLicenseClassID = tdlc.ID
LEFT JOIN GeneralSmall gs ON m1.TypeID = gs.ID
LEFT JOIN fleetchecklist cl ON m1.ChecklistID = cl.ID
WHERE m1.Company_ID = ?compid ";
}
}
I get the error:
Column 'CheckListID' does not belong to table .
and when I try add code m1.ChecklistID As CheckListID, for the CheckListID into the SQL I get the error:
Object cannot be cast from DBNull to other types.
The error happens in this method on the CheckListID line:
protected override void FillObject(DataRow dr)
{
ID = Convert.ToInt32(dr["ID"]);
CheckListID = Convert.ToInt32(dr["CheckListID"]);
LinkedItemID = Convert.ToInt32(dr["LinkedItemID"]);
ItemTitle = Convert.ToString(dr["ItemTitle"]);
Checked = Convert.ToBoolean(dr["Checked"]);
Defect = Convert.ToBoolean(dr["Defect"]);
Resolved = Convert.ToBoolean(dr["Resolved"]);
ResolvedDate = dr["ResolvedDate"].DateTimeOrNull();
ResolvedBy = dr["ResolvedBy"].IntOrNull();
if(dr["Comment"] != DBNull.Value)
Comment = Convert.ToString(dr["Comment"]);
if (dr["ResolvedComment"] != DBNull.Value)
ResolvedComment = Convert.ToString(dr["ResolvedComment"]);
}
You are selecting from fleetchecklist then joining it again at the end. Also LEFT JOIN maintenance m1 ON m1.LinkedID isn't joining it on anything.
SELECT fleetchecklist.*,
cl.ChecklistNo As CheckListNo,
v.VehicleOwnerID AS VehicleOwnerID, v.VehicleOwner AS VehicleOwnerName, v.Reg As VehicleReg,
t.TrailerOwnerID AS TrailerOwnerID, t.TrailerOwner AS TrailerOwnerName, t.Reg As TrailerReg,
vdlc.Description AS VehicleDriverLicenseClassName,
tdlc.Description AS TrailerDriverLicenseClassName,
m1.MaintenanceNo AS MaintenanceNo, m1.Date AS Date
FROM fleetchecklist cl
LEFT JOIN maintenance m1 ON cl.ID = m1.ChecklistID
LEFT JOIN Vehicle v ON m1.LinkedID = v.ID
LEFT JOIN Trailer t ON m1.LinkedID = t.ID
LEFT JOIN Employee ve ON v.VehicleOwnerID = ve.ID
LEFT JOIN Employee te ON t.TrailerOwnerID = te.ID
LEFT JOIN driverlicenseclass vdlc ON ve.DriverLicenseClassID = vdlc.ID
LEFT JOIN driverlicenseclass tdlc ON te.DriverLicenseClassID = tdlc.ID
LEFT JOIN GeneralSmall gs ON m1.TypeID = gs.ID
WHERE m1.Company_ID = ?compid
Also without pointless Aliases
SELECT fleetchecklist.*,
cl.ChecklistNo,
v.VehicleOwnerID, v.VehicleOwner AS VehicleOwnerName, v.Reg As VehicleReg,
t.TrailerOwnerID, t.TrailerOwner AS TrailerOwnerName, t.Reg As TrailerReg,
vdlc.Description AS VehicleDriverLicenseClassName,
tdlc.Description AS TrailerDriverLicenseClassName,
m1.MaintenanceNo, m1.Date
FROM fleetchecklist cl
LEFT JOIN maintenance m1 ON cl.ID = m1.ChecklistID
LEFT JOIN Vehicle v ON m1.LinkedID = v.ID
LEFT JOIN Trailer t ON m1.LinkedID = t.ID
LEFT JOIN Employee ve ON v.VehicleOwnerID = ve.ID
LEFT JOIN Employee te ON t.TrailerOwnerID = te.ID
LEFT JOIN driverlicenseclass vdlc ON ve.DriverLicenseClassID = vdlc.ID
LEFT JOIN driverlicenseclass tdlc ON te.DriverLicenseClassID = tdlc.ID
LEFT JOIN GeneralSmall gs ON m1.TypeID = gs.ID
WHERE m1.Company_ID = ?compid

Multiple joins using linq

This is my query:
var results = from table1 in dtSplitDates.AsEnumerable()
join table2 in dtSplitDates.AsEnumerable() on (int)table1["FID"] equals (int)table2["FID"] into lj
from r in lj.DefaultIfEmpty()
select dtSplitDates2.LoadDataRow(new object[]
{
r["FID"],
r["SLNO"],
r == null ? string.Empty : r["Dates"]
}, false);
Currently i am joining on Column FID - due to which i am getting 36 records (duplicates):
However in order to avoid duplicates i need to join also on SLNO column but i am unable to write that query - please help.
As per my understanding you want two join condition; Try this
var results = from table1 in dtSplitDates.AsEnumerable()
join table2 in dtSplitDates.AsEnumerable()
on new {id1 =(int)table1["FID"], SLno1= (int)table1["SLNO"]}
equals new {id2=(int)table2["FID"], SLno2=(int)table2["SLNO"]} into lj
from r in lj.DefaultIfEmpty()
select dtSplitDates2.LoadDataRow(new object[]
{
r["FID"],
r["SLNO"],
r == null ? string.Empty : r["Dates"]
}, false);
Try to implement with this example:
For Multiple Joins:
var result=(from com in db.Company.AsEnumerable()
join c in db.Country.AsEnumerable() on com.CountryID equals c.CountryID
join s in db.State.AsEnumerable() on com.StateID equals s.StateID
join ct in db.City.AsEnumerable() on com.CityID equals ct.CityID
orderby com.Name
select new CompanyModel()
{
CompanyID = com.CompanyID,
Name = com.Name,
AddressLine1 = com.AddressLine1,
CountryID = com.CountryID,
StateID = com.StateID,
CityID = com.CityID,
Country = c.CountryID,
State = s.StateID,
City = ct.CityID,
Pin = com.Pin,
Phone = com.Phone,
}).Distinct().ToList();

How to Join LINQ to another LINQ

i have a query like this
WITH CTE_KELOMPOKINFORMASI (KelompokInformasi, XBRLItem_ItemId)
AS (
SELECT a.Id AS KelompokInformasi, c.XBRLItem_ItemId
FROM XBRLNamespaces a INNER JOIN XBRLHypercubes b
ON a.XBRLView_ViewId = b.XBRLView_ViewId
INNER JOIN XBRLHypercubeDimensionItems c
ON b.XBRLHypercubeId = c.XBRLHypercube_XBRLHypercubeId
WHERE a.Id like '%KBIK_AAKL%')
SELECT f.KelompokInformasi, e.Name AS DimensionName, c.Id AS Domain,
d.Text AS Description FROM [dbo].[XBRLDefinitionRoleDomainItems] a
INNER JOIN [dbo].[XBRLDefinitionRoleDimensionItems] b
ON a.XBRLDefinitionRole_DefinitionRoleId = b.XBRLDefinitionRole_DefinitionRoleId
INNER JOIN XBRLItems c ON a.XBRLItem_ItemId = c.ItemId
INNER JOIN XBRLLabels d
ON a.XBRLItem_ItemId = d.XBRLItem_ItemId
INNER JOIN XBRLItems e
ON b.XBRLItem_ItemId=e.ItemId
INNER JOIN CTE_KELOMPOKINFORMASI f
ON b.XBRLItem_ItemId=f.XBRLItem_ItemId
WHERE b.XBRLItem_ItemId=f.XBRLItem_ItemId
i want to move this sql query to linq, i realized that CTE is impossible in LINQ. So i divide into 2 parts. First i create a var like this:
var KelompokInformasi = from x in ent.XBRLNamespaces
join y in ent.XBRLHypercubes on x.XBRLView_ViewId equals y.XBRLView_ViewId
join z in ent.XBRLHypercubeDimensionItems on y.XBRLHypercubeId equals z.XBRLHypercube_XBRLHypercubeId
where x.Id.Contains("KBIK")
select new
{
x.Id,
y.XBRLItem_ItemId
};
and in second part i create:
_list = (from a in ent.XBRLDefinitionRoleDomainItems
join b in ent.XBRLDefinitionRoleDimensionItems on a.XBRLDefinitionRole_DefinitionRoleId equals b.XBRLDefinitionRole_DefinitionRoleId
join c in ent.XBRLItems on a.XBRLItem_ItemId equals c.ItemId
join d in ent.XBRLLabels on a.XBRLItem_ItemId equals d.XBRLItem_ItemId
join e in ent.XBRLItems on b.XBRLItem_ItemId equals e.ItemId
join f in KelompokInformasi on b.XBRLItem_ItemId equals (int)f.XBRLItem_ItemId
where (b.XBRLItem_ItemId == (int)f.XBRLItem_ItemId)
select new MappingDomainRepository
{
KI = f.Id,
Dimension = e.Name,
Domain = c.Id,
Description = d.Text
}).ToList();
Where _list is from List<MappingDomainRepository> _list = new List<MappingDomainRepository>();
in my code above, i want to join my _list to var KelompokInformasi. In var kelompokInformasi I've got 47 rows but in _list I've got 0 data return.
What's wrong in my code? is it possible to join my _list to var kelompokInformasi?
You need to change the second part to:
var other = (from a in ent.XBRLDefinitionRoleDomainItems
join b in ent.XBRLDefinitionRoleDimensionItems on a.XBRLDefinitionRole_DefinitionRoleId equals b.XBRLDefinitionRole_DefinitionRoleId
join c in ent.XBRLItems on a.XBRLItem_ItemId equals c.ItemId
join d in ent.XBRLLabels on a.XBRLItem_ItemId equals d.XBRLItem_ItemId
join e in ent.XBRLItems on b.XBRLItem_ItemId equals e.ItemId
join f in KelompokInformasi on b.XBRLItem_ItemId equals (int)f.XBRLItem_ItemId
where (b.XBRLItem_ItemId == (int)f.XBRLItem_ItemId)
select new MappingDomainRepository
{
KI = f.Id,
Dimension = e.Name,
Domain = c.Id,
Description = d.Text,
XBRLItem_ItemId = a.XBRLItem_ItemId
};
...which adds in the XBRLItem_ItemId which use to join to the CTE.
Then join the two together. We have other (above) and KelompokInformasi from the CTE:
var result = from x in KelompokInformasi
join o in other on x.XBRLItem_ItemId equals o.XBRLItem_ItemId
select new {KelompokInformasi = o.KelompokInformasi,
DimensionName = o.Name,
Domain = o.Id,
Description = o.Text
};
..which appears to be the columns you exentually select.

entity framework query, how to select more than 1 table?

i have this query
var resultado = from c in conn.carrera
join u in conn.usuario on c.idusuario equals u.idusuario
join t in conn.texto on c.idtexto equals t.idtexto
where c.estatus == 1
select c;
how do i get something as it:
select c.*,u.*,t.eltexto from carrera c
join usuario u on c.idusuario =u.idusuario
join texto t on c.idtexto = t.idtexto
where c.estatus = 1
you could see in the query i am select c.*, u.* and t.col1, then
how can i get it in EF? because my first query gets only carrera.* but i need more data.
thanks
You could easily return a new object consisting all the properties of the three joined tables:
var resultado = from c in conn.carrera
join u in conn.usuario on c.idusuario equals u.idusuario
join t in conn.texto on c.idtexto equals t.idtexto
where c.estatus == 1
select new
{
c.prop_1,
c.prop_n,
u.prop_1,
u.prop_n,
t.prop_1,
t.prop_n
};
select c.*,u.*,t.eltexto from carrera c
join usuario u on c.idusuario =u.idusuario
join texto t on c.idtexto = t.idtexto
where c.estatus = 1
from c in Carrerra
join u in Usuario on c.idusuario equals u.idusuario
join t in Texto on c.idtexto equals t.idtexto
where c.estatus = 1
select new {
newcolumn1 = c.column1,
c.column2,
usercolumn1 = u.column1,
usercolumn2 = u.column2,
textcolumn = t.column1
}
if you want access to the objects themselves, then you could do
select new {
usario = u,
carrera = c,
texto = t
}
Carrera, Usario, and Texto refer to the Models in your Entity Framework container.

Categories