How to use Linq
A table
Field Birthday
Linq searches for recent birthdays (within 15 days)
from a in Employee where a.PositionStatus == true select new{ a.Name,a.Birthday}
Try below query
var fromdate = DateTime.Now;
var todate = DateTime.Now.AddDays(15);
var result =
(
from a in Employee
where a.PositionStuats==true && a.DateOfBirth.Value.Month >= fromdate.Month &&
a.DateOfBirth.Value.Month <= todate.Month &&
a.DateOfBirth.Value.Day >= fromdate.Day && a.DateOfBirth.Value.Day <= todate.Day
select new{ a.Name,a.Birthday}
).ToList();
Depending on your entity frame work version you can also replace a.DateOfBirth.Value.Month with a.DateOfBirth.Month.
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.
I'm trying to create a basic room availability statement to use with linq to entity framework. I have two tables: 'Room' including columns RoomID/RoomSize and 'Booking' including BookingID/RoomID/StartDate/Enddate.
I have got a working sql statement:
SELECT RoomID, RoomSize from Room
where RoomID NOT IN (SELECT RoomID from booking
where ('08/01/2015' >= [start] AND '08/01/2015' <= [end]) OR ('08/20/2015' >= [start] AND '08/20/2015' <= [end]))
I have got this far with the linq to entity statement:
var rooms = (from r in db.Rooms
where !(((from b in db.Bookings
where (startDate >= b.StartDate && endDate <= b.EndDate) || (endDate >= b.StartDate && endDate <= b.EndDate)).Contains(r.RoomID))
select new AvailableRoom
{
ID = r.RoomID,
Size = r.RoomSize
});
I get an error at the last bracket before .Contains(r.RoomID) saying I should have a select statement but I just can't seem to get it working.
Any suggestions would be welcome.
If you reckon using lambdas would be better/easier please feel free to suggest and example. I'm just not too familiar with them myself.. yet.
Thank you.
You can use LINQ !...Any() for the SQL NOT IN(), like so :
var rooms = (from r in db.Rooms
where !db.Bookings
.Where(b => (startDate >= b.StartDate && endDate <= b.EndDate)
||
(endDate >= b.StartDate && endDate <= b.EndDate)
)
.Any(b => b.RoomID == r.RoomID)
select new AvailableRoom
{
ID = r.RoomID,
Size = r.RoomSize
});
I'm trying to create a sub-query to obtain the latest date from a table, unrelated to the rest of the query.
My query is below. I'd like to select the highest date in a sub-table as a value and project it to my model below.
My other tabe is Feedback and contains a date value and a username field
return (from t1 in db.TaskAppointmentOpens
from t2 in db.Tasks.Where(t => (t.Task_ID == t1.Parent_Task_ID))
from t3 in db.UserNames.Where(t => (t.User_Username == t2.OwnerTypeItem_ID))
where ((t2.Item_ID > 0) && (t2.Type_ID > 0) && (t2.Creator == user) && (t1.AppointmentEnd < DateTime.Now) && (t1.AppointmentStart > EntityFunctions.AddMonths(DateTime.Now, -6)) && (from i in db.AppointmentFeedbacks where i.AppointmentId == t1.ID select i).Count() == 0)
group new {t2, t3} by new {
t2.OwnerTypeItem_ID, t3.Name
} into g
let oldestAppointment = g.Min(uh => uh.t2.Due_Date)
select new TelesalesNeglectedFeedbackModel
{
UserFullName = g.Key.Name,
QtyOutstanding = g.Select(x => x.t2.Task_ID).Distinct().Count(),
OldestAppointment = oldestAppointment
LastDateInOtherTable = HERE <======
}).Take(5).ToList();
You should be able to access the table and field this way:
LastDateInOtherTable = db.Feedback.Max(f => f.Date)
Or use a let clause as you've done for the other column and then assign it later:
let lastDate = db.Feedback.Max(f => f.Date)
...
LastDateInOtherTable = lastDate
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!