Convert from SQL query to Linq Query - sql-to-linq-conversion

Can somebody please change this query for me to Linq
SELECT Causes.CauseTitle,COUNT(Calender.CauseID) AS NumberOfOccurance FROM Calender
LEFT JOIN Causes
ON Calender.CauseID=Causes.CauseID
GROUP BY CauseTitle;
Thanks in advance

Please try the below linq query. I Did not test this. Let me know if there are any issues.
from cal in Calender
join cas in Causes on cal.CauseID equals cas.CauseID into j1
from j2 in j1.DefaultIfEmpty()
group j2 by cas.CauseTitle into grouped
select new { CauseTitle = grouped.Key, NumberOfOccurance = grouped.Count(t=>t.CauseID != null) }

Related

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!

SQL to LINQ - AND Statement in Left Join

I have this SQL query to get all police name that didn't assigned to specified police car.
SELECT policename
FROM police
LEFT OUTER JOIN policecar
ON police.policeid = policecar.policeid
AND carid = 1
WHERE policecar.policeid IS NULL
I want to convert that query to LINQ but I have difficulty to convert AND and WHERE statement. Please give me any direction on this, thanks.
Try this:
var result =
from police in polices
join policecar in policecars.Where(x => x.carid == 1)
on police.policeId equals policecar.policeId into res
where !res.Any()
select police.policeName;

Using LinQ with group by more than one column

I'm Newbi in LinQ, I have problem with group by in linQ.
I wan to query like this:
select
MAX(TCheckpointGrouping.Id) AS CheckpointGroupingId,
MAX(TCheckpointGrouping.MCheckpointId) AS CheckpointId,
MAX(MCheckpoint.Name) AS CheckpointName,
MAX(CAST(MCheckpoint.IsMajor AS VARCHAR)) AS IsMajor,
MAX(TCheckpointGrouping.MIndicatorId) AS IndicatorId,
MAX(MIndicator.Name) AS IndicatorName,
MAX(MCriteria.Id) AS CriteriaId,
MAX(MCriteria.Name) AS CriteriaName,
MAX(MPrinciple.Id) AS PrincipleId,
MAX(MPrinciple.Name) AS PrincipleName,
MAX(TCheckpointGrouping.RelationToCheckPoint) AS RelationToCheckPoint
from TCheckpointGrouping
inner join MCheckpoint on MCheckpoint.Id = TCheckpointGrouping.MCheckpointId
inner join MIndicator on MIndicator.Id = TCheckpointGrouping.MIndicatorId
inner join MCriteria on MCriteria.Id = MIndicator.MCriteriaId
inner join MPrinciple on MPrinciple.Id = MCriteria.MPrincipleId
group by
TCheckpointGrouping.MCheckpointId,
TCheckpointGrouping.MIndicatorId
How can i convert query above into LinQ (VB.NET)
thanks
bestRegards
I'm tempted to convert this SQL query to LINQ for you, but I think that would be a waste of opportunity for you to learn yourself.
There's a great page from Microsoft with lot of VB.NET Linq situations: 101 Linq Samples.
You can even find an example of a Group By using Multiple Columns.
Good learning. :)
I am not sure about this, but you can try it. In select part i have not included all the columns.
var result= from TChkgp in TCheckpointGrouping
join MCpoint in MCheckpoint on TChkgp.Id equals MCpoint.Id
join MIndtor in MIndicator on TChkgp.MIndicatorId equals MIndtor.Id
join MCrteia in MCriteria on MIndtor.Id equals MIndtor.MCriteriaId
join MPrncple in MPrinciple on MCrteia.MPrincipleId equals MPrncple.Id
group TChkgp by new (TChkgp.MCheckpointId,TChkgp.MIndicatorId} into g
select new {
CheckpointGroupingId =TChkgp.Id.Max(),
CheckpointId =TChkgp.MCheckpointId.Max,
....
....
};
you can see one simple example on following link
Group and sum in linq

LINQ translation doesn't give the same results as my SQL query

Hi guys I have this SQL query (MSSQL), I'm doing a query where the result of joins are giving me the "top" row of newest row by date without having duplicates of results, you can find here information of what I'm doing http://goo.gl/Uv0FR The thing is this, I accomplished already the SQL query, Is Working as I'm expecting, I'm getting 1 row for each IDKEY uses in the clause "where pi.PlazaIe in ('','') without duplication
Select * from PlazaI pi
join (
Select * from PlazaE pe where
NOT EXISTS(SELECT 1 FROM PlazaE pe1
WHERE pe.Id_plaza = pe1.Id_plaza AND pe1.Fecha > pe.Fecha AND pe1.Fecha < GETDATE() and pe1.Id_Emp != 0)
) pe on pe.Id_plaza = pieepo.Id_plaza
join Emp e on pe.Id_Emp = e.Id_Emp
join View ct on ct.Id_Nodo = pe.id_nodo
where pi.PlazaIe in ('value1','value2')
The PROBLEM is when I'm trying to convert from SQL to LINQ is just can't make to happened. (I'm new in this world of Linq)
the following is my linq query.
var q1 = (from pe in db.PlazaEmpleados
where !db.PlazaEmpleados.Any
(
pe1 => (pe1.Id_plaza.Equals(pe.Id_plaza) && pe1.Fecha > pe.Fecha && pe1.Id_Emp != 0 && pe1.Fecha > DateTime.Now)
) select pe);
var q2 = (from pi in db.Context
join pe in (q1) on pi.Id_plaza equals pe.Id_plaza
select new EmpVO
{
Id_Nodo = pe.id_nodo,
Id_plaza = pi.PlazaSome,
Num_Plaza = pi.Id_plaza,
});
When I run this linq2sql query I'm getting duplicate results instead of just 1 for each value. So the thing is, I would like to know if someone can convert in a good way the SQL query to LINQ Query or point me where is the error.
thanks in advance.
Your check for the Date is different:
LINQ:
pe1.Fecha > DateTime.Now
SQL:
pe1.Fecha < GETDATE()
Isnt your LINQ supposed to be:
pe1.Fecha < DateTime.Now
I didn't find answer which resolve my problem, so what I finally did is to use the
db.ExecuteQuery<ObjectVO>(sqlQuery);
I know this is not the best practice and also don't resolve the question why my sql query and my linq query don't get the same result set, but non of the previous answer did.
The other thing is my query grown in complexity (new business logic requirement) have to join 7 table and search for Max dates and movement is some of them, so now is more complicated to transform the query to a linq to sql.
Thanks for the support.
this part:
var q1 = from pe in db.PlazaEmpleados
where !db.PlazaEmpleados.Any
(pe1 =>
pe1.Id_plaza.Equals(pe.Id_plaza) &&
pe1.Fecha > pe.Fecha &&
pe1.Id_Emp != 0 &&
pe1.Fecha < DateTime.Now
)
select pe;
In SQL you first use PlazaI then PlazaE- in Linq you both times use PlazaEmpleados.
Put your SQL query to stored procedure an add it to context. Then just call:
var q = context.MyProcedure(new object[] {"value1","value2"});

convert sql to linq sample

I've got a sql statement, but I can't get it working in linq. Can someone show me how I can write the following sql statement as linq?
SELECT * FROM mobileApplication
LEFT JOIN videoMobile ON mobileApplication.id = videoMobile.mobileApplicationId
AND videoMobile.videoId = 257
It's a left join with a where statement on the right table. It works in sql server 2005, but I'd like to write it in linq.
I didn't verify the syntax, but try this...
var mobileApplications = from ma in mobileApplication
join vm in videoMobile on ma.id equals vm.mobileApplicationId into j1
from j2 in j1.DefaultIfEmpty()
where vm.videoId == 257
select ma;
There is a product that will do this for you. I have found it very useful. The product name is Linqer. It is not free, but not expensive, and offers a 30 day trial. I have found very few queries it is not able to convert. It has worked well for me.
http://www.sqltolinq.com/
Its something like:
from ma in mobiledApplication.DefaultIfEmpty()
join vm in videoMobile on new { mobileApplicationId = ma.id, videoId = 257 } equals new { mobileApplicationId = vm.mobileApplicationId, videoId = vm.videoId } into videoMobileApplication
from vma in videoMobileApplication
select vma
The keys being the default if empty and using anonymous objects on the join criteria to incorporate 257 into the join.
I am pretty sure that using a where clause for the 257 will achieve the same result though...
Try some like this:
var query =
from m in mobileApplication
join v in videoMobile
on m.id = v.mobileApplicationId and v.id = 257
select m;
See here:
http://msdn.microsoft.com/en-us/library/bb397676%28v=VS.100%29.aspx
http://msdn.microsoft.com/en-us/magazine/cc163400.aspx