How to convert the following SQL query to Linq? - sql

How to convert following SQL query to Linq?
select day(Ser_CallDate) as OrderDate, count(*) TotalCall
from ServiceCalls
where month(Ser_CallDate) = MONTH(getdate()) and year(Ser_CallDate) = YEAR(getdate())
group by day(Ser_CallDate)
Please help me, thanks

var result = ServiceCalls
.Where(s => s.Ser_CallDate.Month == DateTime.Now.Month
&& s.Ser_CallDate.Year == DateTime.Now.Year)
.GroupBy(s => s.Ser_CallDate)
.Select(g => new {
OrderDate = g.Key,
TotalCall = g.Count()})
.ToList();

Related

How to perform following query in LINQ?

I have a SQL query need to do in LINQ. Can anyone helps in converting?
SELECT *
FROM profile
WHERE ProfileId <> 1221 AND IsActive = 1 AND
ProfileId NOT IN (SELECT ReportingPerson
FROM ReportingPersons
WHERE Employee = 1221)
var reportingPerson = context.ReportingPersons.Where(x =>
x.Employee == 1221)
.Select(c => c.ReportingPerson
).ToList();
var result = context.Profiles
.Where(x =>
x.ProfileId != 1221 &&
x.IsActive &&
!reportingPerson.Contains(x.ProfileId)
.ToList();

How to Convert Sql to Linq with Distinct(id)

select count(distinct LicencePlate) from MT_Vehicle where IsDeleted=0 and CreatedBy = 1
var count = MT_Vehicle.Where(x => x.IsDeleted==0 && x.CreatedBy == 1)
.Select(x => x.LicencePlate)
.Distinct()
.Count();
You can write that as:
var count = db.MT_Vehicle
.Where( v => v.IsDeleted == 0 && v.CreatedBy == 1 )
.Select(v => v.LicencePlate)
.Distinct()
.Count();

SQL with max(date) to LINQ

I have tried to make the following sql in linq with no luck can some help mw with this?
select * from customer c
where companynumber = 1
and status <> 0
and lastdate = (select max(lastdate) from customer where customernumber = c.customernumber)
Gives 22 records
My best try was this:
_ctx.Customers
.Where(r => r.CompanyNumber == companyNumber && r.CustomerNumber != null && r.Status != 0)
.GroupBy(c => c.CustomerNumber)
.Select(g => new
{
name = g.Key,
count = g.Count(),
date = g.Max(x => x.LastEdited)
})
.OrderBy(c => c.name);
Gives 22.000+ records
But not the result as the above SQL
UPDATE:
The following LINQ does the trick ;o)
from a in _ctx.Customers
where a.CustomerNumber != null && a.CompanyNumber == companyNumber
group a by new { a.CustomerNumber } into g
select g.OrderByDescending(a => a.LastEdited).FirstOrDefault() into c
where c.Status == 1
select c
I had to move the where c.Status == 1 into my first select statment

Linq - How to Use NOT IN

I am having following query & i need to write it in linq. I am stuck in NOT IN part.
SELECT A.CODE,
A.DATETIME,
A.DATE
FROM TABLE_IO A
WHERE A.DATE>= '01/06/2015' AND A.DATE<='01/06/2015'
AND A.CODE NOT IN(
SELECT CODE
FROM TABLE_ENTRY B
WHERE A.CODE=B.CODE AND A.DATE=B.ENTRY_DATE AND METHOD='M'
)
How to write NOT IN part?
var data = ctx.TABLE_IO.Where(m=>m.Date >= '01/06/2015' && m.Date <= '01/06/2015')
.Select(m=>m).ToList();
You can use !Any:
DateTime dateToCompare = new DateTime(2015, 6, 1);
var data = ctx.TABLE_IO
.Where(m => m.Date >= dateToCompare && m.Date <= dateToCompare)
.Where(m => !ctx.TABLE_ENTRY
.Any(te => m.Code == te.Code && m.Date == te.ENTRY_DATE && te.METHOD == "M"))
.ToList();
I would prefer this, i'm fairly sure that it will be translated to a performant NOT EXISTS which has also no issues with null values like NOT IN/Contains.
The direct translation of NOT IN/Contains would be this:
var data = ctx.TABLE_IO
.Where(m => m.Date >= dateToCompare && m.Date <= dateToCompare)
.Where(m => !ctx.TABLE_ENTRY.Select(te => te.Code).Contains(m.Code))
.ToList();
Basically you can do something such as (pseudo queries below)
var exclusions = table_B.Where(b => [exclusion condition] ).Select(b => b.Id)
var data = ctx.TABLE_IO.Where(m => !exclusions.Contains(m.Id))

C# + LINQ - inner join

Table: one
Column (PK): employee_ssn
Column: employee_active bit
Table: two
Column (pk): date
Column (FK): employee_ssn
Column: total_income
Column: total_expenses
Working Linq code to sum total_income and total_expenses for the year, per employee:
var SumOfSections = db.two
.Select(x => x)
.Where(x => x.employee_ssn.Equals(xxxxxxxxx))
.Where(x => x.Date.Year.Equals(year))
.GroupBy(x => x.Date)
.Select(g => new
{
Total_Income = g.Sum(x => x.total_expenses),
Total_Expenses= g.Sum(x => x.total_income)
})
.ToArray();
I need to incorporate INNER JOIN to the above to only include active employees. Working SQL:
select two.total_income,total_expenses
from two
INNER JOIN one
ON one.SSN = two.SSN
WHERE one.Active = 1 AND two.Date='1/1/2014' AND two.SSN='xxxxxxxxx';
How can I modify my linq code to what my sql code is doing?
var SumOfSections = (from t in db.two
join o in db.one on t.employee_ssn equald o.employee_ssn
where t.employee_ssn = "xxxxxxxxx" && o.employee_active == true
group t by t.date into g
select new {
Total_Income = g.Sum(x => x.total_expenses),
Total_Expenses= g.Sum(x => x.total_income)
}).ToArray();
I used query syntax because it seems to be more readable.
You can also continue with the notation you are using:
var SumOfSections = db.two.Join(db.one, o=>o.employee_ssn, t=>t.employee_ssn, (o,t)=>new {One = o, Two = t)
.Select(x => x)
.Where(x => x.Two.employee_ssn.Equals(""))
.Where(x => x.Two.date.Year.Equals(1234))
.Where(x=> x.One.employee_active == true)
.GroupBy(x => x.Two.date)
.Select(g => new
{
Total_Income = g.Sum(x => x.Two.total_expenses),
Total_Expenses = g.Sum(x => x.Two.total_income)
})
.ToArray();