How convert linq query to SQL query? - c#

I want convert following LINQ query to SQL query.
var ACTIVITY_ROYALITY_MONTH = from m in db.MiningPermit
join pm in db.Permit_Mineral on m.MINING_PERMIT_ID equals pm.MINING_PERMIT_ID
join r in db.Royality on pm.Permit_Minerals_ID equals r.Permit_Minerals_ID
where r.ORDER_ID == 0 // NULL in server
orderby r.YEAR, r.MONTH
group r by new { m.MINING_PERMIT_ID , r.YEAR, r.MONTH } into mpmr
select mpmr.ToList();

Use Linqpad and recreate the linq (even by bringing in your assemblies) in a C# query. Run the query. Then in the output, there is a selection button of SQL which will show the sql code.

Related

Linq query showing more data than the SQL alternative

I have an linq query like this :
var query = from Romm in RoMM
join rfrsa in RoMmfrsa on Romm.RoMmid equals rfrsa.RoMmid
join frsa in Frsa on rfrsa.Frsaid equals frsa.Fraid
join fra in Fra on frsa.Fraid equals fra.Fraid
where Romm.ActTypeId == 2 && Romm.SegmentId == 4
select new
{
Romm.ActTypeId,
Romm.RoMmid,
frsa.Fraid,
frsa.Frsaid,
Romm.ImpactId
};
And I have SQL code as below :
SELECT romm.ROMMID
, frsa.FRAID
, frsa.FRSAID
, romm.ImpactID
FROM RoMM AS romm
INNER
JOIN RoMMFRSA AS rfrsa
ON romm.RoMMID = rfrsa.RoMMID
INNER
JOIN FRSA AS frsa
ON rfrsa.frsaid = frsa.frsaid
INNER
JOIN FRA AS fra
ON frsa.FRAID = fra.FRAID
WHERE romm.acttypeid = 2
AND romm.segmentid = 4
The SQL only shows one row (which is correct), the linq shows the correct row and then it displays about another 3 rows which is not what we need. I need the linq to show one row which is correct with the SQL. Is this because of maybe many-many relationships ?
Looks like a typo in either the C# or the SQL join:
SQL: ON rfrsa.frsaid = frsa.frsaid
C#: rfrsa.Frsaid equals frsa.Fraid
^^^^^^
mismatch here

SQL to LINQ Convertion error: DISTINCT an Agregate count cannot be converted to LINQ

I have a SQL query and I am trying to convert it to LINQ. But when I do so, I am getting this error:
SQL cannot be converted to LINQ: DISTINCT an Agregate count cannot be converted to LINQ
SELECT
ST_CN_NO,
DN_DT,
count(ST_CN_NO) as totlines,
count(distinct LOC_CODE) as totloc,
sum(SN_QTY)as totscnqty,
sum(SAP_QTY) as totmpqty
from physical_count
where 1=1
group by ST_CN_NO,DN_DT
order by physical_count.ST_CN_NO
So, how can I convert count(distinct LOC_CODE) to LINQ? Is there any way to do so?
This is my LINQ query whithout adding count(distinct LOC_CODE):
from t in db.PHYSICAL_COUNT
where
1 == 1
group t by new {
t.ST_CN_NO,
t.DN_DT
} into g
orderby
g.Key.ST_CN_NO
select new {
ST_CN_NO = (Int32?)g.Key.ST_CN_NO,
g.Key.DN_DT,
totlines = (Int64?)g.Count(),
totscnqty = (Int32?)g.Sum(p => p.SN_QTY),
totmpqty = (Int32?)g.Sum(p => p.SAP_QTY)
}

How to convert PostgreSQL query to Linq to SQL for NHibernate

I am using NHibernate and LINQ to SQL and I want to convert the following SQL query:
select min(T."CustomerName") from public."Jobs" as T group by lower(T."CustomerName");
I want to convert it in LINQ to SQL and add it in a DAO.
Please help.
At last I have found the answer.
Here it is:
return HibernateTemplate.Execute(session => (from r in session.Query<Job>()
group r by r.CustomerName.ToLower()
into g
let c = g.Min(l => l.CustomerName)
orderby c
select c)).ToList();
Thank you people.

Convert from LINQ to SQL query to SQL query

I want to convert LINQ to SQL to SQL query. I know simple LINQ to SQL but don't know about more.
Given below is my Linq to Sql and I want to convert it into Sql query.
from objSql in objContext.DoctorNotes
join objCreatedU in objContext.Users on objSql.CreatedByUserFK equals objCreatedU.UserID into objCU
from tblC in objCU.DefaultIfEmpty()
join objModifiedU in objContext.Users on tblC.ModifiedByUserFK equals objModifiedU.UserID into objMU
from tblM in objMU.DefaultIfEmpty()
select new DoctorNoteBind(objSql)
{
CreatedBy = tblC.UserName,
ModifiedBy = tblM.UserName
}).ToList();
The .DefaultIfEmpty() are used to represent LEFT JOINs (http://msdn.microsoft.com/en-us/library/ms187518(v=sql.100).aspx). You'd expect the equivalent SQL to take the following form:
SELECT
U1.UserName AS CreatedBy,
U2.UserName AS ModifiedBy
FROM
DoctorNotes DN
LEFT JOIN Users U1 ON
U1.UserID = DN.CreatedByUserFK
LEFT JOIN Users U2 ON
U2.UserID = DN.ModifiedByUserFK
-- WHERE ?
-- ORDER BY ?

SQL to Linq equivalent

I've got this stored procedure I'd like to convert to LINQ to SQL, but I'm having a bit of trouble because I'm new to LINQ (and actually, I'm no SQL guru) and I am not getting the expected results. (I tried calling the SPROC from LINQ to SQL but when I send in the Period datetime as parameter on the SPROC I get some error on L2S about the parameter being nullable but I sent it also non-nullable and I still get the same error.) Below is the SQL:
SELECT Persons.IDPerson,Persons.Name,Persons.PaternalName,Departments.DepartmentName,Jobs.Title, Persons.HireDate, Terminations.TerminationDate, Terminations.HireDate
FROM Persons left outer join Terminations on Persons.IDPerson = Terminations.IDPerson
left outer join Departments on Departments.idDepartment = Persons.IdDepartment
left outer join Jobs on Jobs.IDJob = Persons.IDJob
WHERE (Terminations.IDTermination is null OR Terminations.TerminationDate >= #Period)
and Terminations.HireDate <= #Period OR Persons.HireDate <=#Period
ORDER BY Persons.HireDate, Terminations.HireDate asc
This is my LINQ code so far (it does compile but it doesn't give me the records I expect) The Criteria.Period is a nullable datetime:
result = from emp in HRSystemDB.Persons.OfType<Employee>()
join term in HRSystemDB.Terminations on emp.IDPerson equals term.IDPerson into all
from aHire in all.Where(t => (t.IDTermination == null || t.TerminationDate.Date >= Criteria.Period.Value.Date)
&& t.HireDate.Value.Date <= Criteria.Period.Value.Date
|| emp.HireDate.Date <= Criteria.Period.Value.Date).DefaultIfEmpty()
select new DepartmentHeadCountQuery
{
FullName = emp.Name + " " + emp.PaternalName,
Department = emp.Department.DepartmentName,
JobTitle = emp.Job.Title,
TermDate = aHire.TerminationDate,
EHiredDate = emp.HireDate,
TermHireDate = aHire.TerminationDate
};
Thanks in advance.
This (free only for trial) can be usefull: http://www.sqltolinq.com/
Linqer is a SQL to LINQ converter tool.
It will help you to learn LINQ and convert your existing SQL statements.
Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions.
Linqer supports both .NET languages C# and Visual Basic.
And a totally free tool:
http://www.linqpad.net/
LINQPad is also a great way to learn LINQ: it comes preloaded with 200 examples from the book, C# 3.0 in a Nutshell. There's no better way to experience the coolness of LINQ and functional programming.
I know this question it's old, but I think it's need a correct answer, I get to this questing searching for a LINQ equivalent of the IN SQL Keyword and see that the equivalent LINQ code for this query are not provided, maybe the Original author answer this question some time ago, but I leave this for other people searching in the internet:
I got to answers one if you like to have Left Outer Joins:
var query = from emp in context.Persons
join ter in context.Terminations on emp.Id equals ter.IdPerson into terminations
join dep in context.Departments on emp.IdDeparment equals dep.IdDepartment into departments
join job in context.Jobs on emp.IdJob equals job.IdJob into jobs
from ter in terminations.DefaultIfEmpty() //Does an Left Outer Join
from dep in departments.DefaultIfEmpty()
from job in jobs.DefaultIfEmpty()
where (ter.IdTermination == null || ter.TerminationDate >= period)
&& (ter.HireDate <= period || emp.HireDate <=period)
select new
{
emp.Id,
emp.Name,
emp.PaternalName,
dep.DepartmentName,
job.Title,
emp.HireDate,
ter.TerminationDate,
TerminationHireDate=ter.HireDate
};
one using Inner Joins
var query = from emp in context.Persons
join ter in context.Terminations on emp.Id equals ter.IdPerson
join dep in context.Departments on emp.IdDeparment equals dep.IdDepartment
join job in context.Jobs on emp.IdJob equals job.IdJob
where (ter.IdTermination == null || ter.TerminationDate >= period)
&& (ter.HireDate <= period || emp.HireDate <=period)
select new
{
emp.Id,
emp.Name,
emp.PaternalName,
dep.DepartmentName,
job.Title,
emp.HireDate,
ter.TerminationDate,
TerminationHireDate=ter.HireDate
};
the variable context is the Linq to SQL or Linq to Entity Context

Categories

Resources