Sql query to Left Join in Linq to entity - sql-server

I've below SQL query
Select LC.*,LP.[LandingPageName] from [LandingPageCompanies] LC
Left join [LandingPageContent] LP on LP.SubCategoryID=LC.SubCategoryID
where LC.[CategoryID]=17
And i need to convert it into LINQ to entity.
i've tried the following query, But it's working as Inner join
var data = (from t1 in dbSavingContainer.LandingPageCompanies
join t2 in dbSavingContainer.LandingPageContents on t1.SubCategoryID equals t2.SubCategoryID
where t1.CategoryID == CategoryID
select new
{
CategoryID = t1.CategoryID,
CompanyID = t1.CompanyID,
CompanyLink = t1.CompanyLink,
CompanyLogo = t1.CompanyLogo,
CompanyName = t1.CompanyName,
SubCategoryID = t1.SubCategoryID,
LandingPageName = t2.LandingPageName
}).ToList();
Where i'm lacking. ?

Thanks..i just solved it using below query ;)
var data = (from t1 in dbSavingContainer.LandingPageCompanies
join t2 in dbSavingContainer.LandingPageContents on t1.SubCategoryID equals t2.SubCategoryID
into x from y in x.DefaultIfEmpty()
where t1.CategoryID == CategoryID
select new
{
CategoryID = t1.CategoryID,
CompanyID = t1.CompanyID,
CompanyLink = t1.CompanyLink,
CompanyLogo = t1.CompanyLogo,
CompanyName = t1.CompanyName,
SubCategoryID = t1.SubCategoryID,
LandingPageName = y.LandingPageName
}).ToList();

Related

Count in CTE query with variables

I have a query and want to COUNT all the related ids from other table.
I am using CTE and I also assigning variables.
When I print I get all the ids but how can I COUNT the same ids? I mean if I have an id "254aswer" 3 times it should show 3
This is the query:
;WITH cte AS (
select q.fecha, '31' as cdocu, q.Cotizacion__c, cli.codcli,
q."name", q.RUC__c, c.Nombre_contacto__c as atte, a.Direcci_n__c,
q.Referencia__c, q.Requisicion__c, con.mone, q.T_Cambio__c, q.TotalPrice,
(q.TotalPrice*q.IGV__c)/100 as toti,(q.TotalPrice+
(q.TotalPrice*q.IGV__c)/100) as totn, '0' as flag, ven.codven, cd.codcdv,
'00' as codscc,q.fecha as fven ,q.Validez_por__c,'0' as selchk,'0' as
estado,q.Descripcion__c,'0' as word,'0' as frontera,'0' as
idalias,q.T_Cambio__c as tcme,'0'as idcliente,'0' as idcontacto,'0' as
persnt,'0'as flag_rp,'0' as origen,ti.IDdespacho,'0' as nrosal,'0' as
iddirfis,tr.codtra,q.fecha as fecreg,ROW_NUMBER() OVER(ORDER BY
q.Cotizacion__c) AS 'Row1', q.Id
from quote AS q
LEFT JOIN tbl01cor cor ON q.Cotizacion__c = cor.nroini
LEFT JOIN mst01cli cli ON q.RUC__c = cli.ruccli
LEFT JOIN Contact c ON q.RUC__c = c.RUC_contacto__c
LEFT JOIN Account a ON q.RUC__c = a.RUC__c
LEFT JOIN tbl01cdv cd ON q.Condicion__c = cd.nomcdv
LEFT JOIN tbl_tipo_despacho ti ON q.T_Entrega__c = ti.despacho
LEFT JOIN tbl01tra tr ON q.Transportista__c = tr.nomtra
LEFT JOIN consulta con ON q.CurrencyIsoCode = con.CurrencyIsoCode
LEFT JOIN tbl01ven ven ON q.Vendedor__c = ven.nomven
select #fecha = cte.fecha, #cdocu = cte.cdocu, #ndocu = cte.Cotizacion__c, #codcli = cte.codcli, #nomcli = cte."name", #ruccli = cte.RUC__c, #atte = cte.atte,
#dirent = cte.Direcci_n__c, #nrefe = cte.Referencia__c, #requ = cte.Requisicion__c, #mone = cte.mone, #tcam = cte.T_Cambio__c, #tota = cte.TotalPrice, #toti = cte.toti,
#totn = cte.totn, #flag = cte.flag, #codven = cte.codven, #codcdv = cte.codcdv,#codscc = cte.codscc,#fven = cte.fven, #dura =cte.Validez_por__c, #selchk = cte.selchk,
#estado = cte.estado, #obsere = cte.Descripcion__c, #word= cte.word, #frontera = cte.frontera,#idalias = cte.idalias,#tcme = cte.tcme, #idcliente = cte.idcliente,
#idcontacto = cte.idcontacto, #persnt = cte.persnt, #flag_rp= cte.flag_rp, #origen = cte.origen,#tipent = cte.IDdespacho, #nrosal = cte.nrosal,
#iddirfis = cte.iddirfis, #CodTra = cte.codtra, #fecreg = cte.fecreg, #ID = cte.Id
FROM cte
--WHERE cte.fecha >= dateadd(day,datediff(day,0,GETDATE()),0)
WHERE Row1 = #COUNTER +1
SET #ITEM = (Select COUNT(*) from QuoteLineItem where Id = #ID)
PRINT #ITEM
I tried to create a new select like this:
SET #ITEM = (Select COUNT(*) from QuoteLineItem where Id = #ID)
But it only count all the items and I need to show the count for each of the ids. How can I get that?
I fixed it with this:
select count(QuoteId) from QuoteLineItem Where QuoteId = q.Id Group by QuoteId

T-SQL to MS Access SQL

I have a working query in SQL Server, but I fail to convert it to MS Access SQL.
This is the bare working query in SQL Server:
select tblKPIData.id
,tblKPIData.KPI_id
,tblKPI.KPI_Name
,tblKPIData.ImportTimestamp
,tblKPIData.Quantity
,tblKPIData.FinancialMonth
,tblKPIData.FinancialYear
,tblKPIData.Zone_id
,tblZone.ZoneName
,tblKPIData.DMA_id
,tblDMA.DMA_Name
,tblKPIData.TargetOrResult
from tblKPIData
inner join tblKPI
on tblKPI.Id = KPI_id
left outer join tblDMA
on tblDMA.Id = tblKPIData.DMA_id
left outer join tblZone
on tblZone.ID = tblKPIData.Zone_id
inner join tblDashboardKPI
on tblDashboardKPI.KPI_Id = tblKPIData.KPI_id
inner join
( select a.kpi_id
,a.financialMonth
,a.financialYear
,isnull(a.zone_id,0) as zone_id
,isnull(a.dma_id,0) as dma_id
,a.targetorresult
,max(a.importtimestamp) as importtimestamp
from tblKPIData a
group by kpi_id
,financialMonth
,financialYear
,zone_id
,dma_id
,targetorresult) as max_kpi
on (tblKPIData.KPI_id = max_kpi.KPI_id
and tblKPIData.ImportTimestamp = max_kpi.importtimestamp
and tblKPIData.FinancialMonth = max_kpi.FinancialMonth
and tblKPIData.FinancialYear = max_kpi.FinancialYear
and isnull(tblKPIData.Zone_id,0) = isnull(max_kpi.zone_id,0)
and isnull(tblKPIData.DMA_id,0) = isnull(max_kpi.dma_id,0)
and tblKPIData.TargetOrResult = max_kpi.TargetOrResult)
where tblKPIData.FinancialMonth = 'Oct'
and tblKPIData.FinancialYear = 2017
and tblKPIData.KPI_id in (select kpi_id from tblDashboardKPI where tblDashboardKPI.KPI_Id = tblKPIData.KPI_id)
and (tblKPIData.Zone_id = 5 or tblKPIData.DMA_id in (select id from tblDMA where Zoneid = 5))
AND ((tblDashboardKPI.Status) = 1)
and ((tblDashboardKPI.Dashboard_Id) = 6)
I know I have to add brackets, but not exactly sure where. This is what I came up with, but I get an error (Join Expression not supported) and it highlites a piece of code on the first join (tblKPI.Id = KPI_id):
select tblKPIData.id
,tblKPIData.KPI_id
,tblKPI.KPI_Name
,tblKPIData.ImportTimestamp
,tblKPIData.Quantity
,tblKPIData.FinancialMonth
,tblKPIData.FinancialYear
,tblKPIData.Zone_id
,tblZone.ZoneName
,tblKPIData.DMA_id
,tblDMA.DMA_Name
,tblKPIData.TargetOrResult
from (((((tblKPIData
inner join tblKPI
on tblKPI.Id = KPI_id)
left outer join tblDMA
on tblDMA.Id = tblKPIData.DMA_id)
left outer join tblZone
on tblZone.ID = tblKPIData.Zone_id)
inner join tblDashboardKPI
on tblDashboardKPI.KPI_Id = tblKPIData.KPI_id)
inner join
( select a.kpi_id
,a.financialMonth
,a.financialYear
,isnull(a.zone_id,0) as zone_id
,isnull(a.dma_id,0) as dma_id
,a.targetorresult
,max(a.importtimestamp) as importtimestamp
from tblKPIData a
group by kpi_id
,financialMonth
,financialYear
,zone_id
,dma_id
,targetorresult) as max_kpi
on (tblKPIData.KPI_id = max_kpi.KPI_id)
and tblKPIData.ImportTimestamp = max_kpi.importtimestamp
and tblKPIData.FinancialMonth = max_kpi.FinancialMonth
and tblKPIData.FinancialYear = max_kpi.FinancialYear
and isnull(tblKPIData.Zone_id,0) = isnull(max_kpi.zone_id,0)
and isnull(tblKPIData.DMA_id,0) = isnull(max_kpi.dma_id,0)
and tblKPIData.TargetOrResult = max_kpi.TargetOrResult)
where tblKPIData.FinancialMonth = 'Oct'
and tblKPIData.FinancialYear = 2017
and tblKPIData.KPI_id in (select kpi_id from tblDashboardKPI where tblDashboardKPI.KPI_Id = tblKPIData.KPI_id)
and (tblKPIData.Zone_id = 5 or tblKPIData.DMA_id in (select id from tblDMA where Zoneid = 5))
AND ((tblDashboardKPI.Status) = 1)
and ((tblDashboardKPI.Dashboard_Id) = 6)
What am I doing wrong?

need to convert posted sql query to LINQ

How do i make that query in linq please advise
select *
from tblPermission
where RoleId in (select roleid from tbluserrole where userid = #userID)
When converting from SQL to LINQ, convert in the order of the LINQ phrases. If your SQL has table aliases, use them as the range variables. If a query contains a sub-query, translate it first in the same way. Translate IN into Contains.
var roles = from ur in tbluserrole where ur.userid == parmUserId select ur.RoleId;
var ans = from p in tblPermission
where roles.Contains(p.RoleId)
select p;
You can do this in 2 ways:
var roles = tbluserrole.Where(e => e.userid == userId).Select(e => e.roleid).ToList();
var prmsns = tblPermission.Where(e => roles.Contains(e.RoleId).ToList()
or
var prmsns = (from e in tblPermission
let roles = tbluserrole.Where(f => f.userid == userId).Select(f =>
f.roleid).ToList();
where roles.Contains(e.RoleId)
select e).ToList();
from
EDIT:
you can do this with inner join like this
var prmsns = (from e in tblPermission
join f in tbluserrole on tblPermission.RoleId equals tbluserrole.roleid
where f.userId == userId
select e).ToList();

Converting SQL inner join, group by and order to LINQ

I have created an SQL query as follows:
SELECT s.FullName, s.[Id], COUNT(t.[User]) AS Records
FROM dbo.AspNetUsers s INNER JOIN dbo.PBBuilds t
ON s.Id = t.[User]
GROUP BY t.[User], s.[FullName], s.[Id]
ORDER BY COUNT(t.[User]) DESC
I'm attempting to convert this to a LINQ query, and this is how far i have got:
Dim results = From H In context.Users
Join C In context.PBBuilds On H.Id Equals C.User
Group By C.User Into
Could anyone please advise.
Try this query -- (make changes accordingly though)
var results = From U In context.AspNetUsers
Join P In context.PBBuilds On U.Id Equals P.User
Group By new { P.User, U.FullName } Into g
Orderby COUNT(P.User) Descending
select new {
FullName = U.FullName,
ID = U.Id,
Records = COUNT(P.User)
};
try code
var results = From U In context.AspNetUsers
Join P In context.PBBuilds On U.Id Equals P.User
Group new {U,P} By new { P.User, U.FullName } Into g
select new {
FullName = g.FirstOrDefault().U.FullName,
ID = g.FirstOrDefault().U.Id,
Records = g.Count()
}).OrderByDescending(c=>c.Records).ToList();

How to Left Join two Parent-Child tables (i.e. 4 tables)

We have the following database structure:
How can we query for all the data that belongs to a specific client and group? (An example written using Entity Framework 6 would be great.)
We could do something like this:
var parentChild1 = dbcontext.Parent1.Include(p => p.Child1).Select(p => p.ClientId = clientId).ToList();
var parentChild2 = dbcontext.Parent2.Include(p => p.Child2).Select(p => p.GroupId = groupId).ToList();
// And the manually join the values in parentChild2 with the objects in parentChild1.
// But there has to be a better way than this.
I'm thinking something like this; but can't figure out how to wire up child1(s) with child2(s):
void GetData(int clientId, int groupId)
{
var query = (from p1 in dbcontext.Parent1
from c1 in dbcontext.Child1
where p1.ClientId == clientId && c1.Parent1Id == p1.Id
join p2 in dbcontext.Parent2.Where(p2 => p2.GroupId == groupId)
on p1.Id equals p2.Parent1Id into p2groups
join c2 in dbcontext.Child2 on c1.Id equals c2.Child2Id into c2groups
from p2g in p2groups.DefaultIfEmpty()
from c2g in c2groups.DefaultIfEmpty()
select new Parent1
{
Parent2s = p2g,
//Child1s = c2g ??? How to wire up child1s with child2s?
};
}
The following sql statement should return all the data that belongs to a single parent1Id and groupId, from all the tables.
SELECT *
FROM Parent1 p1
LEFT JOIN Parent2 p2 ON(p1.Id = p2.Parent1Id AND p2.GroupId = #groupId)
LEFT JOIN Child1 c1 ON(p1.id = c1.Parent1Id)
LEFT JOIN Child2 c2 ON(c1.id = c2.Childe1Id AND p2.id = c2.Parent2Id)
WHERE p1.Id = #Id
The child joins are left joins since I assume not all parents have children, but the parents join is an inner join since you need the groupid as well as the parent1 id.

Resources