linq2sql - How to use raw SQL to get a count from DB? - c#

Currently, for a getting a count of items in a complicated query with joins i am doing something like this --
string q = #"SELECT f.FILE_ID
FROM [Email.Link] AS l INNER JOIN Email AS e ON (l.EMAIL_ID = e.EMAIL_ID)
INNER JOIN File AS f ON (e.EMAIL_ID = f.EMAIL_ID)
WHERE l.EntityId = 123";
var files = Context.ExecuteQuery<File>(q);
return files.Count();
any better way to do this, rather than getting all the ID's back and counting?
I would prefer to do a SELECT Count(*) and get the int back in linq.

Instead of returning FILE_ID collection you can return the ready COUNT as a part of your SQL query:
string q = #"SELECT COUNT(f.FILE_ID)
FROM [Email.Link] AS l INNER JOIN Email AS e ON (l.EMAIL_ID = e.EMAIL_ID)
INNER JOIN File AS f ON (e.EMAIL_ID = f.EMAIL_ID)
WHERE l.EntityId = 123";
return Context.ExecuteQuery<Int32>(q);

try this
string q = #"SELECT COUNT(f.FILE_ID)
FROM [Email.Link] AS l INNER JOIN Email AS e ON (l.EMAIL_ID = e.EMAIL_ID)
INNER JOIN File AS f ON (e.EMAIL_ID = f.EMAIL_ID)
WHERE l.EntityId = 123";
return Context.ExecuteQuery<Int32>(q).FirstOrDefault();

Related

Is it possible to use WHERE by some IF condition for PostgreSQL?

I have the following SQL request for a report.
select customers."AppId", second_dep "SecondDeps", first_dep "FirstDeps",
customers_count "Customers", registrations "Registrations"
From (select Count("AppId") as customers_count, "AppId"
FROM "Customers"
join "Advertisers" A on "Customers"."AdvertiserId" = A."AdvertiserId"
join "Categories" C2 on "Customers"."CategoryId" = C2."CategoryId"
where A."Name" in (:AdvertiserNames)
AND C2."Name" = :CategoryName
GROUP BY "AppId"
) as customers
left join
(select C."AppId", count(CE.*) as second_dep
from "CustomerEvents" as CE
inner join "Customers" C on CE."CustomerId" = C."CustomerId"
WHERE "EventType" = 'deposit'
and "Again" = TRUE
GROUP BY C."AppId") as dep2 on customers."AppId" = dep2."AppId"
left join
(select C."AppId", count(CE.*) as first_dep
from "CustomerEvents" as CE
inner join "Customers" C on CE."CustomerId" = C."CustomerId"
WHERE "EventType" = 'deposit'
and "Again" = false
GROUP BY C."AppId") as dep on customers."AppId" = dep."AppId"
left join
(select C."AppId", count(CE.*) as registrations
from "CustomerEvents" as CE
inner join "Customers" C on CE."CustomerId" = C."CustomerId"
WHERE "EventType" = 'registration'
GROUP BY C."AppId") as regs on regs."AppId" = customers."AppId";
The string with problem is
where A."Name" in (:AdvertiserNames)
I would like to skip it if AdvertiserNames is empty. Is it possible? Ok, I can check it on the code side, but this way will leads me to copy whole request with some small difference (I mean if AdvertiserNames is empty run SQL without where A."Name" in (:AdvertiserNames)). Or I can use concatenation to get suitable SQL. I dont like this way too.
About my technology stack. It's .NET Core 2.2 with PostgreSQL. Here is the code of whole report method:
public IQueryable<ByApplicationsReportModel> ByApplications(string category, List<string> advertisers)
{
var rawSql = new RawSqlString(#"
select customers.""AppId"", second_dep ""SecondDeps"", first_dep ""FirstDeps"",
customers_count ""Customers"", registrations ""Registrations""
From (select Count(""AppId"") as customers_count, ""AppId""
FROM ""Customers""
join ""Advertisers"" A on ""Customers"".""AdvertiserId"" = A.""AdvertiserId""
join ""Categories"" C2 on ""Customers"".""CategoryId"" = C2.""CategoryId""
where A.""Name"" in (#AdvertiserNames)
AND C2.""Name"" = #CategoryName
GROUP BY ""AppId""
) as customers
left join
(select C.""AppId"", count(CE.*) as second_dep
from ""CustomerEvents"" as CE
inner join ""Customers"" C on CE.""CustomerId"" = C.""CustomerId""
WHERE ""EventType"" = 'deposit'
and ""Again"" = TRUE
GROUP BY C.""AppId"") as dep2 on customers.""AppId"" = dep2.""AppId""
left join
(select C.""AppId"", count(CE.*) as first_dep
from ""CustomerEvents"" as CE
inner join ""Customers"" C on CE.""CustomerId"" = C.""CustomerId""
WHERE ""EventType"" = 'deposit'
and ""Again"" = false
GROUP BY C.""AppId"") as dep on customers.""AppId"" = dep.""AppId""
left join
(select C.""AppId"", count(CE.*) as registrations
from ""CustomerEvents"" as CE
inner join ""Customers"" C on CE.""CustomerId"" = C.""CustomerId""
WHERE ""EventType"" = 'registration'
GROUP BY C.""AppId"") as regs on regs.""AppId"" = customers.""AppId""");
var advertisersParam = new NpgsqlParameter("AdvertiserNames",
string.Join(",", advertisers) );
var categoryParam = new NpgsqlParameter("CategoryName", category);
return _context.ByApplicationsReportModels
.FromSql(rawSql, categoryParam, advertisersParam);
}
Any ideas?
You might try changing where A.""Name"" in (#AdvertiserNames) to where (A.""Name"" in (#AdvertiserNames) or #AdvertiserNames = '').
Instead of concatenating your advertisers into a string, you could just pass an array of strings directly to your query:
var advertisersParam = new NpgsqlParameter("AdvertiserNames", advertisers));
In SQL, instead of using the x IN (#advertisers) construct, you would need to change to x = ANY (#advertisers).
Note: you would still need an additional clause if you want the check to pass when #advertisers is empty.

Cannot make 5 consecutive "joins" in LINQ?

I have this rather complex query in SQL server 2008:
declare #LanguageID as int = 1
select k.datePublish, k.dateEditing, k.dateTables
from TableAreasLevel1 as areaL1
inner join TableAreasLevel2 as areaL2
on areaL1.LanguageID = areaL2.LanguageID and
areaL1.CodeAreaLevel1 = areaL2.CodeAreaLevel1
inner join TableAreasLink as link
on areaL2.CodeAreaLevel1 = link.CodeAreaLevel1 and
areaL2.CodeAreaLevel2 = link.CodeAreaLevel2 and
inner join TableProducts as tblProds
on tblProds.CodeAreaLevel1 = areaL1.CodeAreaLevel1 and
tblProds.CodeAreaLevel2 = areaL2.CodeAreaLevel2
inner join TableSI_Products as prod
on prod.SiAreaCode = link.SiAreaCode
inner join TableCalendar as k
on k.KodTableSI_Products = tblProds.KodTableSI_Products
where areaL1.LanguageID = #LanguageID and
prod.Code = 'some string' and
k.LanguageID = #LanguageID and
tblProds.LanguageID = #LanguageID;
I am trying to develop the same query in LINQ, but I get error when I try join the table TableProducts, i.e the third consecutive join.
Here is my LINQ query:
List<Tuple<DateTime, DateTime, DateTime>> dates = (from areaL1 in gpe.TableAreasLevel1
join areaL2 in gpe.TableAreasLevel2
on new { areaL1.CodeAreaLevel1, areaL1.LanguageID } equals
new { areaL2.CodeAreaLevel1, areaL2.LanguageID }
join link in gpe.TableAreasLink
on new { areaL2.CodeAreaLevel1, areaL2.CodeAreaLevel2, areaL2.RbrOblastNivo2} equals
new {link.CodeAreaLevel1, link.CodeAreaLevel2}
join tblProds in gpe.TableProducts
on tblProds. // The name tblProds is not in the scope of the left side of 'equals'
);
Is the problem connected with how the tables are designed or, something else I should check for?
Any ideas, why tblProds is not visible in the scope of the LINQ query?
You are using Query as your guide something like:
on k.KodTableSI_Products = tblProds.KodTableSI_Products
but take a look at your linq:
on new { areaL1.CodeAreaLevel1, areaL1.LanguageID } equals
it has two fields. I think its not a good idea.
linq join something like
var dates = (from areaL1 in gpe.TableAreasLevel1
join areaL2 in gpe.TableAreasLevel2
on areaL1.PKFields equals areaL2.PKFields
where areaL1.CodeAreaLevel1== areaL2.CodeAreaLevel1 && areaL1.LanguageID = areaL2.LanguageID
Select new YournewClass{YournewClass.Field1=areaL1.fields1, And so on}
)
You can do to join the other tables with aliases.
Sorry need to go for now.
I'm giving you an idea.
Hope it helps.

C# LINQ Query with group by, having and where clause invalid

I have the following Linq queries which are getting the error below. My question is how can I use the T_EquipmentCompetency.Competency in a where clause but not have it in the group by or select list. I am fairly new to LINQ queries. Is there something that I am missing here?
using (EntitiesModel dbContext = new EntitiesModel())
{
var competencyForMachine = (from eq in dbContext.T_Equipmentcompetencies
where eq.MachineId == machineId
select eq.CompetencyId);
var competencyForEmployees = (from sm in dbContext.T_OHS_Skillsmatrices
join em in dbContext.T_Employees on sm.EmployeeID equals em.EmployeeID
where competencyForMachine.Contains(sm.CompentencyID)
group sm by new {sm.EmployeeID,em.FirstNameSTR,em.LastNameSTR} into g
where g.Count() == competencyForMachine.Count()
select new {g.Key.EmployeeID, g.Key.FirstNameSTR,g.Key.LastNameSTR});
foreach(var employee in competencyForEmployees)
{
RadMenuItem employeeItem = new RadMenuItem { Text= employee.FirstNameSTR + " " + employee.LastNameSTR, Value = employee.EmployeeID.ToString()};
Item.Items.Add(employeeItem);
}
}
This is the error I am getting
Telerik.OpenAccess.RT.sql.SQLException: Column
'dbo.T_EquipmentCompetency.CompetencyId' is invalid in the select list
because it is not contained in either an aggregate function or the GROUP BY clause.
The sql I am trying to emulate works in SQL Server
declare #MachineId int = 1
select sm.EmployeeID,em.FirstNameSTR,em.LastNameSTR
from T_OHS_SkillsMatrix sm
inner join T_Employees em on sm.EmployeeID = em.employeeId
where sm.CompentencyID in ( select CompetencyID
from T_EquipmentCompetency
where MachineId = #machineId
)
group by sm.EmployeeID,em.FirstNameSTR,em.LastNameSTR
having count(*) = (select count(*) from T_EquipmentCompetency where MachineId = #MachineId)
you got it mispelled
select eq.CompetencyId --- different spelling
sm.CompentencyID
while in sql sql server
where sm.CompentencyID in ( select CompentencyID

How to make a right join using LINQ to SQL & C#?

I have a problem creating the following SQL Statement using LINQ & C#
select c.IDAddenda, c.Descripcion
from CatAddendas c
right join EmpresaAddenda e on e.IDAddenda = c.IDAddenda
where e.rfc = 'SUL010720JN8'
order by c.IDAddenda asc
I got this:
public IEnumerable<CatAddenda> TraeAddendas(string rfc)
{
DataClasses1DataContext dc = new DataClasses1DataContext(...);
return (from adds in dc.EmpresaAddendas
cats.IDAddenda into joined
where adds.RFC == rfc
select adds.CatAddenda);
}
This is not doing a right join, so any ideas?
var RightJoin = from adds in dc.EmpresaAddendas
join cats in CatAddendas
on adds.IDAddenda equals cats.IDAddenda into joined
from cats in joined.DefaultIfEmpty()
select new
{
Id = cats.IDAddenda,
Description = cats.Descripcion
};
var results = from e in EmpresaAddenda
join c in CatAddendas
on e.IDAddenda equals c.IDAddenda into f
from c in f.DefaultIfEmpty()
select new
{
ID = c.IDAddenda,
Description = c.Descripcion
};
You can apply where and order by on the results.

LINQ and joining on selects

I have the following SQL:
select o.tekst as Enhet,
coalesce(f.Antall,0) as AntallF,
coalesce(f.snitt,0) as SnittF,
coalesce(b.antall,0) as AntallB
from tblhandlingsplan hp
inner join tblorg o on hp.eierorgid = o.orgid
left outer join (select f.handlingsplanid, count(t.tiltakid) as Antall, coalesce(avg(convert(float,t.status)),0) as Snitt from tblhandlingsplanforbedring f left outer join tblhandlingsplantiltak t on f.forbedringsid = t.forbedringsid group by f.handlingsplanid) f on hp.handlingsplanid = f.handlingsplanid
left outer join (select b.handlingsplanid, count(b.bevaringsid) as Antall from tblhandlingsplanbevaring b group by b.handlingsplanid) b on hp.handlingsplanid = b.handlingsplanid
where utsendingsid = 1
Which works exactly how I want it... Now I'm trying to convert this to LINQ...
I have gotten this far
from h in TblHandlingsplans
join o in TblOrgs
on h.EierOrgID equals o.OrgID
join f in TblHandlingsplanForbedrings
on h.HandlingsplanID equals f.HandlingsplanID into f2
join b in TblHandlingsplanBevarings
on h.HandlingsplanID equals b.HandlingsplanID into b2
where h.UtsendingsID == 1
select new {
Enhet = o.Tekst,
AntallF = f2.Count(),
AntallB = b2.Count()
}
however now I'm stuck... I can't for the life of me figure out how to include the average part from the SQL solution... Any takers?
I'm thinking of shoving the whole thing into a SP and leave it with that...
var query1 = from a in DB.Table1
select new
{
Id = a.Id,
Average = a.B.Average()
};
var query2 = from b in DB.Table2
join c in query1 on b.Id equals c.Id
select c;
Just freehanded it, so it might not actually work, but is that the kind of thing you're trying to do? That would result in a single SQL query being created when query2 was used.

Categories