Rewrite Entity Framework LINQ query into T-SQL - c#

How can I rewrite the following Linq query into normal T-SQL?
var list = (from t in context.ParentTable
where t.ChildRecords.Count == t.ChildRecord.Count( c => c.BooleanColumn )
select t).ToList();
Thanks in advance...

Something like this, but you'll need to determine the relationship between the ParentTable and ChildRecord tables to make it work, I'm just guessing at the cr.ParentTableId = pt.ParentTableId part.
select pt.*
from ParentTable pt
where not exists
(select 1
from ChildRecord cr
where cr.ParentTableId = pt.ParentTableId
and cr.BooleanColumn = 0)
On a side note the Linq could be changed to the following instead.
var list = (from t in context.ParentTable
where t.ChildRecords.All(c => c.BooleanColumn)
select t).ToList();

Related

LINQ Select newest records that have distinct ForeignKeyId column

I have the following SQL query:
SELECT
table1.Id AS EinAusgangId,
table1.Ausgabedatum,
table1.Rueckgabedatum,
table1.WerkzeugId,
cpmWerkzeug.Name
FROM cpmEinAusgang AS table1
INNER JOIN cpmWerkzeug ON table1.WerkzeugId = cpmWerkzeug.Id
WHERE table1.Id = (SELECT MAX(Id) AS Expr1
FROM dbo.cpmEinAusgang
WHERE table1.WerkzeugId = WerkzeugId)
My aim is to convert the whole query into a LINQ statement for further use in a .Net Application. I already converted joined tables to LINQ but is it also possible to use a select in the where clause?
This is what I got so far, which gives me almost the same result as the SQL statement above, but has major errors when the table cpmEinAusgang contains more then one record for one cpmWerkzeug
using (var dbContext = new cpmEntities())
{
var werkzeuge = from w in dbContext.cpmWerkzeug
join e in dbContext.cpmEinAusgang
on w.Id equals e.WerkzeugId
where e.Rueckgabedatum == null
orderby w.Name
select w;
return werkzeuge.ToList();
}
Has anyone an idea how to achieve the above sql in linq?
Thanks for your help. :)
EDIT:solved (see below)
var werkzeugeImUmlauf = from w in dbContext.cpmWerkzeug
join e in dbContext.cpmEinAusgang
on w.Id equals e.WerkzeugId
where e.Id == dbContext.cpmEinAusgang.Where(x => x.WerkzeugId == e.WerkzeugId).Max(x => x.Id) select w;
This is the final solution. As mentioned by Mittal in his answer, it is possible to write a sub-query in LINQ.
Yes, you can write Sub Query in LINQ as well.
var werkzeuge = from w in dbContext.cpmWerkzeug
join e in dbContext.cpmEinAusgang
on w.Id equals e.WerkzeugId
where w.id = (dbContext.cpmEinAusgang.Max(x => x.id)) AND w.WerkzeugId = WerkzeugId

Select where IN using LINQ

Hello I'm trying to use IN condition in LINQ.
I have the following query:
select * from unitphotos Where MarketingFileTypeID = 2
AND UnitTypeID in (Select UnitTypeID from unitTypes Where PropertyID = 1)
I think I can't make it in only one LINQ query, so I did this:
var listUnitTypes = (from ut in db.unittypes
where ut.PropertyID == propertyID
select new { ut.UnitTypeID }).ToList();
var getPropertyPhotos = (from up in db.unitphotos
where listUnitTypes.Contains(up.UnitTypeID)
select up).ToList();
However, it gives me a syntax error inside Contains(up.UnitTypeID): "Argument 1: cannot convert from 'int' to 'anonymous type int UnitTypeID'
Does anyone know what I am doing wrong?
Thanks
var getPropertyPhotos = (from up in db.unitphotos
where unittypes.Any(ut => ut.PropertyID == propertyID && ut.UnitTypeId == up.UnitTypeID)
select up).ToList();
I think this should work. Haven't tried it since I don't have the db though so ymmv.
Also, yours should work if instead of select new { ut.UnitTypeID } you just put select ut.UnitTypeID
You have anonymous type here
var listUnitTypes = (from ut in db.unittypes where ut.PropertyID == propertyID select new { ut.UnitTypeID }).ToList();
And then try to use it in Linq To Entity:
var getPropertyPhotos = (from up in db.unitphotos
where listUnitTypes.Contains(up.UnitTypeID)
select up).ToList();
Seems like Linq to Entity won`t know what that type is.
So you can replace
select new { ut.UnitTypeID })
with
select { ut.UnitTypeID })
as #anakic sad before
And then create 1 query by Linq
var listUnitTypes = (from ut in db.unittypes where ut.PropertyID == propertyID select ut.UnitTypeID);
var getPropertyPhotos = (from up in db.unitphotos where listUnitTypes.Contains(up.UnitTypeID) select up).ToList();
By that you force Linq to Sql create complicated query that should be able to handle your problem.
I think that the way that you are approaching the problem forcing a sub-select is going to end up having you going back to the database more than you have to. I don't have an IDE available right now to bang out the correct LINQ syntax, but why not change your approach from thinking in terms of a SQL sub-select to that of a JOIN? Here is the SQL that I would start with and then translate that to LINQ:
SELECT p.*
FROM unitphotos p
INNER JOIN unitTypes u
ON u.UnitTypeID = p.UnitTypeID
AND u.PropertyID = 1
WHERE p.MarketingFileTypeID = 2

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);

LINQ Projected Filtering C#

I want to filter my LINQ query based on an included table but am having some trouble.
Here is the original statement, which works:
return
this.ObjectContext.People.
Include("Careers").
Include("Careers.Titles").
Include("Careers.Titles.Salaries");
Now I'm trying to filter on Careers using projected filtering but am having trouble. It compiles but it leaves out the Titles and Salaries tables, which causes runtime errors, and I can't seem to add those tables back in:
var query1 = (
from c in
this.ObjectContext.People.
Include("Careers").
Include("Careers.Titles").
Include("Careers.Titles.Salaries")
select new
{
c,
Careers = from Careers in c.Careers
where Careers.IsActive == true
select Careers
});
var query = query1.AsEnumerable().Select(m => m.c);
return query.AsQueryable();
How can I include the titles and salaries tables in the filtered query?
You can simplify your query considerably, which should resolve your issue. I'm assuming that you want all people with at least 1 active career:
var query =
from c in
this.ObjectContext.People.
Include("Careers").
Include("Careers.Titles").
Include("Careers.Titles.Salaries")
where c.Careers.Any(c => c.IsActive);
return query;
I would try something like,
var query = from p in ObjectContext.People
join c in ObjectContext.Careers on p equals c.Person
where c.IsActive
select p;

Sub Query in LINQ

I have an SQL Query as given below
SELECT ui.PageStyleCss
FROM UserImages ui
WHERE ui.UserImageId IN
( SELECT inv.UserImageId
FROM Invitation inv
JOIN InviteeEmails invEmails ON
inv.InviteID = invEmails.InviteID
WHERE invEmails.InviteGUID = #InviteGUID
)
How can I write this in LINQ?
Thanks
My wild guess is that you're using LINQ to SQL. It would be nice if you mentioned this, along with details of your model. Guessing at its structure...
var q = from ui in Context.UserImages
where ui.Invitations.Any(i => i.InviteeEmails.Any(e => e.InviteGuid = inviteGuid))
select ui.PageStyleCss;
from ui in db.UserImages
where (from inv in db.Invitations
join invEmails from InviteeEmails
on inv.InviteId equals invEmails.InviteId
where invEmails.InviteGUID == inviteGUID
select inv.UserImageId).Contains(ui.UserImageId)
select ui.PageStyleCss
(not sure if it compiles or not)
I have to assume there's a better way...this is pretty much a direct translation.

Categories

Resources