Unable to convert SQL Query to LINQ Query for Left Outer Join - sql

Problem Statement:
I'm trying to convert one of my Sql to linq query, but I'm unable to get the desired output which i need. Can anyone suggest me what i should do?
SQL Query:
SELECT AssetTagging.AssetID, AssetTagging.AssetDescription, [Return].RequestStatus
FROM AssetTagging
LEFT OUTER JOIN [Return] ON AssetTagging.AssetID = [Return].AssetID
LEFT OUTER JOIN Issue ON AssetTagging.AssetID = Issue.AssetID
WHERE (Issue.AssetID IS NULL) OR ([Return].RequestStatus = 'Approved')
Linq Query I'm using:
var result = (from at in db.AssetTagging.AsEnumerable()
join r in db.Return on at.AssetID equals r.AssetID
orderby at.AssetID
where !db.Issue.Any(issue=>issue.AssetID==at.AssetID) || r.RequestStatus=="Approved"
select new globalTestModel
{
model1=at
}).ToList();
//I know that in Linq query I'm using Inner join instead of Left Join,but i'm getting error if i use left join instead of inner join?
What am I doing wrong??
Any suggestion to get desired query like Sql in Linq?
Asset Tag table:
Issue table:
Return table:
Desired Output :

You need to remove .AsEnumerable(), because you want your query to be translated to sql. Right now it would be using linq-to-objects and if you are using a left join with linq-to-object you need to check for null reference exceptions. rt could be null, so rt.RequestStatus would throw an exception.
*I believe rt should be r in your example
You can't project to an existing entity, so you need to change your select to:
select new PocoClass
{
model1=at
}
//New class definition
public PocoClass
{
public AssetTagging model1 { get; set; }
}

You need to do like this:
var result = from at in db.AssetTagging
join r in db.Returns on at.AssetID equals r.AssetID into a
from returns into a.DefaultIfEmpty()
join i in db.Issues on at.AssetID equals I.AssetID into b
from issues into b.DefaultIfEmpty()
where issues.AssetID != null || returns.RequestStatus == "Approved"
select new
{
AssetID = at.AssetID,
AssetDescription = at.AssetDescription,
Status = returns != null ? returns.RequestStatus : null
}.ToList();

try like following:
from at in db.AssetTagging
join r in db.Return on at.AssetID equals r.AssetID into res1
from atr in res1.DefaultIfEmpty()
join i in db.Issues on i.AssetID==at.AssetID into res2
from obj in res2.DefaultIfEmpty()
select at
where i.AssetID == null || r.RequestStatus equals "Approved"
Just make two times left outer join and then do filter on where condition.
Also have first look at this msdn article about left outer join using linq.

Try the following I am assuming that you still want the cases where r is null unless r is not null and request status = approved.
You have to check to verify r!=null before checking the request status and you will still need to include when r is null to get the complete result set. I haven't tested this, but this should put you in the right direction.
Good luck.
var result = (from at in db.AssetTagging
join r in db.Return.DefaultIfEmpty()
on at.AssetID equals r.AssetID
join i in db.Issue.DefaultIfEmpty()
on at.AssetID equals i.AssetID
where
(r == null || (r!=null && r.RequestStatus == "Approved"))
|| i == null
select new {
at.AssetID,
at.AssetDescription,
IssueID = (i!=null) ? i.IssueID : null),
ReturnID = (r!=null) ? r.ReturnID: null),
ReturnStatus = (r!=null)
? r.ReturnStatus
: null}).ToList();

I know this isn't exactly what you've asked for, but it might be useful anyway.
If you have access to the database to execute SQL queries, I would suggest creating a view. You can then drop the view into your DBML file the same way as you would with a table, and have much simpler Linq expressions in your C# code.
CREATE VIEW [Asset_Issue_Return_Joined] AS
SELECT AssetTagging.AssetID, AssetTagging.AssetDescription, [Return].RequestStatus
FROM AssetTagging
LEFT OUTER JOIN [Return] ON AssetTagging.AssetID = [Return].AssetID
LEFT OUTER JOIN Issue ON AssetTagging.AssetID = Issue.AssetID
WHERE (Issue.AssetID IS NULL) OR ([Return].RequestStatus = 'Approved')

Here is the complete query
var result = (from assetTagging in db.AssetTagging
join return0 in db.Return on assetTagging.AssetID equals return0.AssetID into returns
from return0 in returns.DefaultIfEmpty()
join issue in db.Issue on assetTagging.AssetID equals issue.AssetID into issues
from issue in issues.DefaultIfEmpty()
where issue.AssetID == null || return0.RequestStatus == "Approved"
select new
{
assetTagging.AssetID,
assetTagging.AssetDescription,
return0.RequestStatus
}).ToList();

Related

Where there is no equality (SQL)

I have wrote this clause:
WHERE ec.etudiant = po.utilisateurEtudiant
With this, i have the student where this equality.
Now, i would like to transform this request. I want to get "For each student with the id "ec.etudiant" that i don't find in "po.utilisateurEtudiant"... i do something.
How can i get it?
If possible avoid LEFT JOIN ON: i am looking for a solution in the WHERE directly (for a specific reason linked to Symfony and my code).
Thank you for your answers. 7,8,9 was exemple. I need a real dynamic request which is able to only keep the difference between "po.utilisateurEtudiant" (contain for EXAMPLE 7,8) and "ec.etudiant"(contain 7,8,9, so i want that my request return me ONLY 9). And only keep the part of "po.utilisateurEtudiant"that ""ec.etudiant" doesn't contain. I tried with NOT EXISTS for 1 hours and i never get what i want :/ My complet request (Symfony 4):
{
return $em->createQuery(
"SELECT u.nomUtilisateur, u.prenomUtilisateur, ec.id AS ec_id
FROM App\Entity\CoursPlanning h
INNER JOIN App\Entity\Cours c
JOIN App\Entity\ProfCours p
JOIN App\Entity\Utilisateur u
JOIN App\Entity\CoursPlanning cp
JOIN App\Entity\EtudiantCours ec
JOIN App\Entity\PlageHoraire w
JOIN App\Entity\DateCours d
JOIN App\Entity\Formation f
JOIN App\Entity\Pointage po
WHERE u.roles = '[\"ROLE_USER\"]'
AND cp.cours = '".$idCours."'
AND cp.dateCours = '".$idDate."'
AND po.cours = cp.id
AND po.plageHoraire = cp.plageHoraire
AND po.utilisateurEtudiant = u.id
AND NOT EXISTS (SELECT 1 FROM App\Entity\EtudiantCours es
WHERE po.utilisateurEtudiant = es.etudiant )
"
)->getResult();
}
This request return me an empty result. But if I do (in the NOT EXISTS): "po.utilisateurEtudiant = 7", i get the 8. Or : if I do ""po.utilisateurEtudiant = 8", i get the 7.
Thank you for advance!
You would use not exists:
select ec.*
from ec
where not exists (select 1
from po
where ec.etudiant = po.utilisateurEtudiant
);

LINQ to Entities returns empty list but it's SQL equivalent returns results

I'm sure this is something fairly common... I'm joining two entities with a mapping table and attempting to load back all relationships.
public IEnumerable<Clinic> ClientClinics(Guid clientId)
{
var clinics =
from c in _appDbContext.Clinics
join ccm in _appDbContext.ClientClinicMappings on c.ClinicId equals ccm.ClinicId
join cli in _appDbContext.Clients on ccm.ClientId equals cli.ClientId
where cli.ClientId == clientId && !c.DeletedAt.HasValue
select c;
return clinics.ToList();
}
I'm getting no results when I should be... I turned on the db logging and here's the generated SQL:
SELECT [c].[ClinicId], [c].[Address], [c].[City], [c].[CreatedAt], [c].[CreatedBy], [c].[DeletedAt], [c].[DeletedBy], [c].[ModifiedAt], [c].[ModifiedBy], [c].[Name], [c].[Phone], [c].[State], [c].[Zip]
FROM [Clinic] AS [c]
INNER JOIN [ClientClinicMapping] AS [ccm] ON [c].[ClinicId] = [ccm].[ClinicId]
INNER JOIN [Client] AS [cli] ON [ccm].[ClientId] = [cli].[ClientId]
WHERE ([cli].[ClientId] = #__clientId_0) AND [c].[DeletedAt] IS NULL
When I paste in my GUID that I'm searching with, I'm able to get results from SQL.
Anyone have any suggestions to where I should be looking or what to be trying?

Convert a SQL query to LINQ query

I have the following SQL query
SELECT *
FROM LOC l
JOIN CLA c ON l.IdLoc = c.IdLoc
JOIN FA f on c.IdCla = f.IdCla
LEFT JOIN CON co ON f.IdCla = co.IdCla
AND co.DeletedDate IS NULL
AND co.IdUser = f.IdUser
WHERE f.IdUser = 7
AND f.DeletedDate IS NULL
I would like to convert it to LINQ but I'm absolutely not at ease with LEFT JOIN and "temp table" with LINQ.
Moreover, I tried to convert it but it seems it is impossible to create a join clause with a WHERE inside in LINQ (Linqer told me that and Linqpad doesn't seem able to convert from SQL to LINQ in free version)
Could you give me clue ?
Thanks a lot
I think you are looking for something like this. I left out the select clause so that you can pull out what you need. Things to note:
To join multiple columns, create anonymous types. The field names in the anonymous types must match.
To create a =NULL condition, create a variable name that matches the field name in the other entity. Set it =null but coerce it to the nullable data type of the field you are setting it equal to.
Edit: Updated query to move where clause to joins
from l in LOC
join c in CLA
on l.IdLoc equals c.IdLoc
join f in FA
on new { c.IdCla, IdUser = 7, DeletedDate = (DateTime?)null }
equals new { f.IdCla, f.IdUser, f.DeletedDate }
join co in CON
on new { f.IdCla, DeletedDate = (DateTime?)null, f.IdUser }
equals new { co.IdCla, co.DeletedDate, co.IdUser } into lj
from l in lj.DefaultIfEmpty()

Convert SQL with multiple join into LINQ

I would like to know how can i change the following sql statement into Linq or Lambda Extension in C#
SELECT m.mdes as AgeGroup,COUNT(DISTINCT(mbcd))as "No.of Member" FROM mageg m
LEFT JOIN (select distinct(mbcd) ,mage
FROMtevtl
JOIN mvipm
ON tevtl.mbcd = mvipm.mvip
WHERE datm >= '2014-04-01'
AND datm <= '2014-04-30'
)vip
ON m.tage >= vip.mage AND m.fage <= vip.mage
GROUP BY m.mdes
I manage to do the first half of the LINQ statement. Not sure If it is correct
here is the first half. I do not know how to connect with the left join.
(from mem in mvipms
from log in tevtls
from grp in magegs
where mem.mage >=grp.fage && mem.mage <=grp.tage && mem.mvip.Equals(log.mbcd)
&& log.datm >= DateTime.Parse("2014-04-01") && log.datm <= DateTime.Parse("2014-04-30")
select new {mem.mvip,grp.mdes}).Distinct()
Pls advice. I am using the MSSQL 2008 and VS2010.
Thanks a million.
I am no expert on LINQ, but since no-one else has answered, here goes!
Firstly you cannot (AFAIK) do a LINQ join on anything other than equals so the structure of your LEFT JOIN has to change. Partly for debugging purposes, but also for readability, I prefer to layout my LINQ in bite-size chunks, so what I would do in your case is something like this (assuming I have understood your data structure correctly):
var vip = (from t in tevtl
join v in mvipl
on t.mbcd equals v.mvip
where t.datm >= new DateTime(2014, 4, 1) && t.datm <= new DateTime(2014, 4, 30)
select new { t.mbcd, v.mage }).Distinct();
var mv = from m in magegl
from v in vip
where m.tage >= v.mage && m.fage <= v.mage
select new
{
m.mdes,
v.mbcd
};
var gmv = from m in mv
group m by new { m.mdes } into grp
select new
{
mdes = grp.Key.mdes,
CountMBCD = grp.Count()
};
var lj = from m in magegl
join v in gmv
on m.mdes equals v.mdes into lhs
from x in lhs.DefaultIfEmpty()
select new
{
AgeGroup = m.mdes,
CountMBCD = x != null ? x.CountMBCD : 0
};
By way of explanation. mv is the equivalent structure for your left join in that it has the relevant where clause, but obviously it does not contain any nulls - it is equivalent to an INNER JOIN. gmv is a group on mv, so is still effectively an INNER JOIN. Then to pick up the missing mdes (if any) I re-join on magel with the added syntax DefaultIfEmpty() - this converts the join into the equivalent of a LEFT OUTER JOIN.
Without any sample data, I haven't been able to test this, but I hope it gives you enough to point you in the right direction!

Linq to SQL and outer apply

I'm trying to convert "SQL Outer Apply" to Linq.
The SQL is:
select Currencies.Name, Currencies.Sign ,a.ActualPrice
from Currencies
outer apply (select CurrencyID,ActualPrice from Prices
where ProductID=5 and Currencies.ID=Prices.CurrencyID)a
I have tried the following Linq but got one row, instead of row for each currency as the SQL statement gives me.
from c in Currencies
from p in Prices.DefaultIfEmpty()
where p.ProductID.Equals(5) && c.ID==p.CurrencyID
select new {c.Name, p.ActualPrice}
Any solution for this?
Try this:
var result =
Currencies.Select(c => new
{
Name = c.Name,
Sign = c.Sign,
ActualPrice = Prices.Where(p => p.ProductID == 5 &&
p.CurrencyID == c.ID)
.FirstOrDefault()
});
I am not sure if this returns the correct result, because I don't know what happens, when the subselect in outer apply returns multiple rows...