Convert SQL query to LINQ with EXISTS and Dates - c#

I am new to using LINQ and I'm trying to convert a SQL query to linq within MVC 5.
My query is a follows:
SELECT COUNT(Core.CoreName) FROM Core WHERE Core.DCID = #0
AND EXISTS (SELECT * FROM AspNetUsers,Response
WHERE Core.CoreID = AspNetUsers.CoreID
AND Response.UserID = AspNetUsers.Id
AND Core.DCID = #1
AND YEAR( Response.CreatedOn ) = YEAR( getDate() )
AND MONTH( Response.CreatedOn ) = MONTH( getDate() ));
Using Linqer I was able to get this but it doesnt seem to work due to the dates:
from Core in
(from Core in db.Core
where
Core.DCID == #0 &&
(from Response in db.Response
where
Core.CoreID == Response.AspNetUsers.CoreID &&
Core.DCID == #1 &&
Response.CreatedOn.Value.Year == Convert.ToDateTime(DateTime.Now).Year &&
Response.CreatedOn.Value.Month == Convert.ToDateTime(DateTime.Now).Month
select new {
Response,
Response.AspNetUsers
}).Single() != null
select new {
Core.CoreName,
Dummy = "x"
})
group Core by new { Core.Dummy } into g
select new {
Column1 = g.Count(p => p.CoreName != null)
}
Can someone please help me fix the linq query or help create a new linq query from the sql. Thanks.

Related

How to search with Linq query in multiples columns and bind into datagridview?

I am using C# and Entity Framework and I would like to select in database with some filter condition. Which comes from a simple SQL query like this:
SELECT *
FROM EMPLOYEE
WHERE ACTIVE = 1 (FNAME LIKE '%KEY%' OR LNAME LIKE '%KEY%' OR ADDRESS LIKE '%KEY%')
ORDER BY LASTUPDAATE DESC;
I using in Linq query as below:
var query = (from e in db.TBLEMPLOYEE
where (e.ACTIVE == 1 AND
(e.FNAME.Contains(text.ToString().Trim())
|| e.LNAME.Contains(text.ToString().Trim())
|| e.ADDRESS.Contains(text.ToString().Trim())))
select e).OrderByDescending(e => c.LASTUPDATE);
if (query.Any())
{
int i = 0;
foreach (EMPLOYEE item in query)
{
i += 1;
int newrow = grid.Rows.Add();
grid.Rows[newrow].Cells[0].Value = item.ID.ToString();
grid.Rows[newrow].Cells[1].Value = i.ToString();
grid.Rows[newrow].Cells[2].Value = item.FNAME.ToString();
grid.Rows[newrow].Cells[3].Value = item.LNAME.ToString();
grid.Rows[newrow].Cells[4].Value = item.ACTIVE.ToString();
}
}
But I get an error in the linq query while running:
The function evaluation requires all threads to run.
Unable to evaluate the expression. Operation not supported. Unknown error: 0x80070057.
Any suggestions please?
Thank you in advance.
Ada.
Fix your query:
var seachText=text.Trim();
var query =db.TBLEMPLOYEE
.Where( e=> (e.ACTIVE == 1)
&& ( ( EF.Functions.Like(e.FNAME,$"%{seachText}%")
|| ( EF.Functions.Like(e.LNAME,$"%{seachText}%")
|| ( EF.Functions.Like(e.ADDRESS,$"%{seachText}%") ) )
.OrderByDescending(c => c.LASTUPDATE)
.ToList();
Here is the working.
var query = (from e in db.TBLEMPLOYEE
where (e.ACTIVE == 1 AND
(e.FNAME.Contains(text.ToString().Trim())
|| e.LNAME.Contains(text.ToString().Trim())
|| e.ADDRESS.Contains(text.ToString().Trim())))
select e).OrderByDescending(e => c.LASTUPDATE).ToList();
Thank you very much all.

LINQ to SQL ,Join tables to get distinct result?

I am trying to write a LINQ query that will get me some distinct values from two SQL Server data tables.
I have two tables named, Facility_Cost_TBL and Tenant_Bills_TBL.
I then have a column that is named Nursing_Home_Name which I am trying to get the distinct data from.
This is my effort in LINQ , however it does not work,
var name = (from f in dataContext.Facility_Cost_TBLs
join t in dataContext.Tenant_Bills_TBLs on f.Tenant_Code equals t.Tenant_Code
where f.Tenant_Code == code && f.Date_Month == date.Month && f.Date_Year == date.Year
select new {Facility_Cost_TBL = f, Tenant_Bills_TBL = t}).Distinct();
And this is a working SQL statement I made that does what I want via T-SQL.
SELECT DISTINCT Nursing_Home_Name
FROM (SELECT Nursing_Home_Name
FROM Facility_Cost_TBL
WHERE Date_Year = 2016 AND Date_Month = 10 AND Tenant_Code = 664250
UNION SELECT Nursing_Home_Name
FROM Tenant_Bills_TBL
WHERE Year_Data = 2016 AND Month_Data = 10 AND Tenant_Code = 664250)
a
Could someone show me what LINQ sytax AND what LINQ extension method query would look like?
Please try following
var names = ((from f in dataContext.Facility_Cost_TBLs
where f.Tenant_Code == "664250" && f.Date_Month == "10" && f.Date_Year == "2016"
select new { Nursing_Home_Name = f.Nursing_Home_Name }).
Union(
from t in dataContext.Tenant_Bills_TBLs
where t.Tenant_Code == "664250" && t.Date_Month == "10" && t.Date_Year == "2016"
select new { Nursing_Home_Name = t.Nursing_Home_Name })).ToList();
Hope this will help you
Try this to see if this works. LINQ to SQL: Multiple joins ON multiple Columns. Is this possible?
var name = (from f in dataContext.Facility_Cost_TBLs
join t in dataContext.Tenant_Bills_TBLs equals on new { f.Tenant_Code, f.Date_Month, f.Date_Year } equals new { t.Tenant_Code, t.Date_Month, t.Date_Year }
where f.Tenant_Code == code && f.Date_Month == date.Month && f.Date_Year == date.Year
select new {Facility_Cost_TBL = f, Tenant_Bills_TBL = t}).Distinct();

Converting SQL to linq with a right join (advanced)

I have the following SQL statement:
SELECT dh.*
FROM table1 w
LEFT OUTER JOIN table2 dh
on w.CBranch = dh.CBranch
AND w.CWorkstation = dh.CWorkstation
AND w.CNumber = dh.CNumber
RIGHT OUTER JOIN table3 dl
on dh.Id = dl.DispatchHeaderId
AND w.CLine = dl.CLine
AND w.CLineVersion = dl.CVersion
where w.ItemStatus = 9
AND dh.Shipping = 0
ORDER BY dh.CNumber ASC
I am beginner in Linq and not sure how to do advanced linq.
Could someone please guide me writing equivalent linq for this.
I am using C#, EF4.
I have managed to get till here, but not sure f this is correct.
var wos = scope.Context.table1.Where(
a => a.ItemStatus == (short)LineStatus.Packed)
.GroupBy(a => new { a.CNumber, a.CBranch, a.CWorkstation})
.Select(a => a.FirstOrDefault()).ToList();
var headerGroups = new List<IEnumerable<table2>>();
foreach(var status in wos)
{
if (status == null)
{
continue;
}
var headerList = scope.Context.table2s.Where(
b => b.CBranch == status.CBranch &&
b.CNumber == status.CNumber &&
b.CWorkstation == status.CWorkstation).ToList();
if (headerList != null && headerList.Any())
{
headerGroups.Add(headerList);
}
};
use defaultifemty() method in following link way....
http://smehrozalam.wordpress.com/2009/06/10/c-left-outer-joins-with-linq/

Convert T-SQL to LINQ using the WHERE IN clause with a Nested Subquery

How would the following T-SQL query be written in LINQ using the WHERE IN clause and a subquery:
SELECT a.IncidentID,
a.OccurWhen,
a.OccurWhere,
a.Description
FROM buIncidentDetail a
WHERE a.IncidentID IN (SELECT IncidentID
FROM buPerson
WHERE IsDeleted = 0
AND (NameFirst LIKE '%%'
OR NameLast LIKE '%%')
)
OR a.IncidentID IN (SELECT IncidentID
FROM buInjury
WHERE IsDeleted = 0
AND (TimeLossEstimateTerms LIKE '%%'
OR ResultOtherDesc LIKE '%%')
)
Before marking this as a possible duplicate, all the other examples I found were using an array, i.e. – (“1”, “2”, “3”). I’m looking for one that specifically demonstrates the use of a subquery.
You turn the queries inside out and start with the inner queries first, and then applying the result of those to the outer query.
int? incidentID;
var person = buPerson.Where(
p => p.IsDeleted == 0
&& (!string.NullOrWhitespace(p.NameFirst)
|| !string.NullOrWhitespace(p.NameLast)).FirstOrDefault();
if ( person != null )
incidentID = person.IncidentID;
else {
var incident = buInjury.Where(
i => i.IsDeleted == 0
&& (!string.NullOrWhitespace(i.TimeLossEstimateTerms)
|| !string.NullOrWhitespace(i.ResultOtherDesc)).FirstOrDefault();
if ( incident != null )
incidentID = incident.IncidentID;
}
if ( incidentID.HasValue() )
{
var detail = buIncident
.FirstOrDefault(j=>j.IncidentID.Value)
.Select(j => new { k => new {
ID = k.IncidentID,
When = g.OccurWhen,
Where = g.OccurWhere,
Description = g.Description };
if ( detail != null )
Console.WriteLine( "{0}, {1}, {2}, {3}",
detail.IncidentID,
detail.OccurWhen,
detail.OccurWhere,
detail.Description);
}
else
Console.WriteLine("No incident found");

SQL into LINQ to Entities

I have a big problem.
I'm for last 5 year SQL-boy, but now I need to convert my SQL query into LINQ to entity C# format.
Because I'm new in LINQ (complex statements) right now I need fast help.
Thank's in advance.
P.S. also I need some advices, some start point to start rapidly to learn LINQ to entities.
Here is my SQL (direct from my app(#endDate,#endDate and #glChartID remain as parameters also in my c# app)):
SELECT budget.accountid,
budget.perioddate,
budget.lastyear,
budget.thisyear,
budget.budget,
budget.operplan,
budget.forecast,
glchart.accounttype,
glchart.headertype
FROM budget INNER JOIN glchart ON budget.accountid = glchart.id
WHERE budget.accountid = #glChartID AND budget.perioddate BETWEEN #startDate and #endDate AND glchart.headertype NOT LIKE 'Header%'
UNION
SELECT glchart.id,
budget.perioddate,
SUM(ISNULL(budget.lastyear, 0)),
SUM(ISNULL(budget.thisyear, 0)),
SUM(ISNULL(budget.budget, 0)),
SUM(ISNULL(budget.operplan, 0)),
SUM(ISNULL(budget.forecast, 0)),
glchart.accounttype,
glchart.headertype
FROM budget INNER JOIN glchart ON budget.accountid = glchart.id
WHERE budget.accountid
IN
(SELECT g.id FROM glchart g
WHERE g.code >= glchart.code AND g.code <
CASE
WHEN glchart. headerlevel = 1 AND
(SELECT MAX(g3.code)
FROM glchart g3
WHERE g3.headerlevel = 1
) = glchart.code
THEN
(SELECT MAX(g2.code)
FROM glchart g2
WHERE g2.code >= g.code)
ELSE
(SELECT MIN(g2.code)
FROM glchart g2
WHERE g2.code > glchart.code AND
g2.headerlevel = glchart. headerlevel) END ) AND
glchart.id = #glChartID AND
budget.perioddate BETWEEN #startDate AND #endDate AND
glchart.headertype LIKE 'Header%'
GROUP BY glchart.id, budget.perioddate, glchart.accounttype, glchart.headertype
Until today, I managed (thanks to DOK)how to do it and this is how my LINQ is look like right now:
var query = ((ObjectQuery<Budget>)(
from budgets in this.ObjectContext.Budgets
join glcharts in this.ObjectContext.GLCharts on new { AccountID = budgets.AccountID } equals new { AccountID = glcharts.ID }
where
(!(from glC in this.ObjectContext.GLCharts
where Convert.ToInt16(glC.Code) >= Convert.ToInt16(glcharts.Code) && glC.Code != (Convert.ToInt64(glcharts.HeaderLevel) == 1 &&
(from g3 in this.ObjectContext.GLCharts
where Convert.ToInt64(g3.HeaderLevel) == 1
select new {g3.Code}).Max(p => p.Code) == glcharts.Code ?
(from g2 in this.ObjectContext.GLCharts
where Convert.ToInt16(g2.Code) >= Convert.ToInt16(glC.Code)
select new {g2.Code}).Max(p => p.Code) :
(from g2 in this.ObjectContext.GLCharts
where Convert.ToInt16(g2.Code) > Convert.ToInt16(glcharts.Code) && g2.HeaderLevel == glcharts.HeaderLevel
select new {g2.Code}).Min(p => p.Code))
select new {glC.ID}
).Contains(new { budgets.AccountID }) &&
glcharts.ID == 2376 && budgets.PeriodDate >= StartDate &&
budgets.PeriodDate <= EndDate &&
glcharts.HeaderType.StartsWith("Header"))
).Contains(new { budgets.AccountID }) && glcharts.ID == 2376 && budgets.PeriodDate >= StartDate && budgets.PeriodDate <= EndDate && glcharts.HeaderType.StartsWith("Header")
group new {glc = glcharts, b = budgets}
by new {
glcharts.ID,
budgets.PeriodDate,
glcharts.AccountType,
glcharts.HeaderType
} into g
select new {
AccountID = (System.Int32?)g.Key.ID,
PeriodDate = (System.DateTime?)g.Key.PeriodDate,
LastYear = g.Sum(p => ((System.Decimal?)p.t.LastYear ?? (System.Decimal?)0)),
ThisYear = g.Sum(p => ((System.Decimal?)p.t.ThisYear ?? (System.Decimal?)0)),
Budget = g.Sum(p => ((int?)p.t.Budget1 ?? (int?)0)),
OperPlan = g.Sum(p => ((System.Decimal?)p.t.OperPlan ?? (System.Decimal?)0)),
Forecast = g.Sum(p => ((System.Decimal?)p.t.Forecast ?? (System.Decimal?)0)),
AccountType = g.Key.AccountType,
HeaderType = g.Key.HeaderType
}));
return query;
But in THIS LINE: .Contains(new { budgets.AccountID }) I'm getting next error :
Error 8'System.Linq.IQueryable' does not contain a definition for 'Contains' and the best extension method overload 'System.Linq.ParallelEnumerable.Contains(System.Linq.ParallelQuery, TSource)' has some invalid arguments
Does anybody have an idea where I'm wrong?
Thanks to everyone.
You might find some help in this excellent reference site.
That will lead you to, for example, two examples for UNION.
If you really must start out at this level of difficulty, you might consider breaking your SQL down into pieces and getting them working bit by bit. Do the first SELECT without the JOIN or WHERE, then add those one at a time. Then do the second SELECT the same way. Then add the UNION.
By the time you get this one worked out, SQL-boy, you will definitely be LINQ-man!

Categories