I have database
Table room: id,name
Table table: id, id_room
Table WorkPanel: id, id_table, **date**.
I use (date == date, and WorkPanel have record with table):
var nowWorkPanels = from a in context.WorkPanels where a.date == date select a;
but I do not understand how to make a check at that time and in this room there is a record
You are obviously not showing all of the fields in your tables, but if your navigational properties are set up correctly, your query will look something like:
from wp in context.WorkPanels
where wp.date == date && wp.Table.id_room == roomId
select wp;
or if you want to query by room name:
from wp in context.WorkPanels
where wp.date == date && wp.Table.Room.name == roomName
select wp;
I prefer the more concise method chaining syntax, though:
context.WorkPanels.Where(wp => wp.date == date && wp.Table.id_room == roomId);
Related
I have a table which has structure like below :
JobListings:
JobID
CompanyID
Status
ActiveDate
ExpiryDate
CreationDate
Now I want to calculate below statistics based on conditions:
Active
OnHold
Closed
Filled
Expired
Now because of some data corruption, I had a problem in ActiveDate field which contains date like this for some jobs : "0001-01-01"
So what I want to do is if ActiveDate has data like "0001-01-01" then
Consider ExpiryDate column else consider ActiveDate only.
I am trying to retrieve this statistics for the first day of month till today.
Here is my query:
var statistics = (from j in context.Job
where j.CompanyID == 100 &&
(j.ActiveDate == "0001-01-01" ? (j.CreationDate >= fromDate && j.CreationDate <= toDate):
(j.ActiveDate >= fromDate && j.fromDate <= today))
group j by j.Status into g
select new
{
Id = g.Key,
Statistics = g.Count()
});
Is there a better way to rewrite this query?
I'm trying to get a list of students based on their status, grouped by their college.
So I have three tables, Students and Colleges. Each student record has a status, that can be 'Prospect', 'Accepted' or 'WebApp'. What I need to do is get a list of students based on the status selected and then display the College's name, along with the number of students that go to that college and have their status set to the status passed in. I think this needs to be an aggregate query, since the counts are coming from the string Status field.
I'm not sure how to do this in MS SQL, since the count is coming from the same table and it's based on the status field's value.
Here is the start of my query, which takes in the search parameters, but I can't figure out how to filter on the status to return the counts.
SELECT Colleges.Name, [Status], Count([Status])
FROM Students
JOIN Colleges ON Students.UniversityId = Colleges.id OR Students.+College = Colleges.Name
GROUP BY Students.[Status], Colleges.Name
ORDER BY Colleges.Name;
Accepts = Status('Accepted')
WebApps = Status('WebApp')
Total = Sum(Accpets + WebApps)
Select
Colleges.Name,
SUM(Case when Students.Status like 'Accepted' then 1 else 0 end) Accepts,
SUM(Case when Students.Status like 'WebApp' then 1 else 0 end) WebApps,
COUNT(*) Total
from Students
join Colleges on Students.UniversityId = Colleges.Id OR Students.CurrentCollege = Colleges.Name
Group by Colleges.Name
The LINQ:
var results =
(from c in db.Colleges // db is your DataContext
select new
{
CollegeName = c.Name,
AcceptedStatus = db.Students.Count(r => r.Status.ToUpper() == "ACCEPTED" && (r.UniversityId == c.Id || r.CurrentCollege == c.Name)),
WebAppStatus = db.Students.Count(r => r.Status.ToUpper() == "WEBAPP" && (r.UniversityId== c.Id || r.CurrentCollege == c.Name)),
Total = db.Students.Count(s => s.UniversityId == c.Id || s.CurrentCollege == c.Name)
}).ToList();
Try this http://www.linqpad.net/
Its free and you can convert the linq to sql queries
What would be the best approach for converting this SQL to linq?
I've earlier made views in the database based on such an sql, and then query the view with linq. But I've would like to know if there are other approaches.
The SQL finds the assigned object for an task. The task table contains three foreign key columns, as the assigned to may be from Department, Position or a Person. Only one is allowed.
SQL:
SELECT id,
title,
assigned_to = (case
when idAssignedDepartment is not null then (select description from department where id = idAssignedDepartment)
when idAssignedPosition is not null then (select description from position where id = idAssignedPosition )
when idAssignedPerson is not null then (select fullname from person where id = idAssignedPerson )
end)
FROM task
Using LinqToEF
You can write it like this:
var q = from t in task
from dep in department.Where(x => x.id == t.idAssignedDepartment).DefaultIfEmpty()
from pos in position.Where(x => x.id == t.idAssignedPosition).DefaultIfEmpty()
from per in person .Where(x => x.id == t.idAssignedPerson).DefaultIfEmpty()
select new
{
t.id,
t.title,
assigned_to = t.idAssignedDepartment != null ? dep.description :
t.idAssignedPosition != null ? pos.description :
t.idAssignedPerson != null ? per.fullname :
null
};
Using LINQ to MySQL
MySQL TABLE Definition
ID binary(16) PK
UtcTriggerTime datetime NOT NULL
PersonID binary(16) NOT NULL FK
Status int(11) NOT NULL
I have a array of 1000s of PersonIDs(Guids) and for each of the PersonID I would like to pick matching records from the table with the following criteria:
UtcTriggerTime >= PREDEFINED_DATE_TIME (e.g. UtcNow - 30days)
AND
Status=1 OR Status=2
I am currently using a
foreach(var personID in personIDsArray){
var qryResult = (from a in AlertObjects.AlertsTriggered
where a.PersonID == personID &&
(a.Status == 1 || a.Status == 2) &&
a.UtcTriggerTime >= PREDEFINED_DATE_TIME
select a).ToArray();
}
What are the possible options to optimise this for performance? Or is there?
I tried putting an Index on (UtcTriggerTime, PersonID, Status) and then used the array of PersonIDs to do it in one query as follows, but it was even slower which when I thought about makes sense:
var qryResult = (from a in AlertObjects.AlertsTriggered
where personIDsArray.Contains(a.PersonID) &&
(a.Status == 1 || a.Status == 2) &&
a.UtcTimeTriggered >= PREDEFINED_DATE_TIME
group a by a.PersonID into alerts
select alerts).ToArray();
It seems to me that you are dealing with typical Select N+1 problem which is caused by
group a by a.PersonID into alerts
select alerts
part.
Could you look in the generated SQL and see what it looks like?
Also there is no need to put Status in index if there not many values because the increase on the performance will be minimal.
If my quess is right you can look on these question to see how the problem can be handled:
How to Detect Select n+1 problems in Linq to SQL?
http://www.west-wind.com/weblog/posts/2009/Oct/12/LINQ-to-SQL-Lazy-Loading-and-Prefetching
I'm not familiar with MySql but it seems to me that this link could be helpful in diagnosing which queries are slow.
http://www.electrictoolbox.com/show-running-queries-mysql/
I am trying to convert a complex (and rather hacky) dynamic SQL query in to a LINQ query.
I have the following LINQ query so far:
var results = (
from c in Customers
from d in MonthCalendar
join f in Facilities on c.CustomerCode equals f.CustomerCode
join p in ProjectedCashFlows on f.FacilityId equals p.FacilityId into pj
from p in pj.DefaultIfEmpty()
where d.ExpectedYear == currentYear
&& f.FacilityStatusId == 1
&& (p.ExpectedYear == null || d.ExpectedYear == p.ExpectedYear)
&& (p.ExpectedMonth == null || d.ExpectedMonth == p.ExpectedMonth)
&& c.PrimaryArmId == userId
&& (p.ProjectedCashFlowStatusId == null || p.ProjectedCashFlowStatusId != 4)
select new
{
CustomerCode = c.CustomerCode,
CustomerName = c.CustomerName,
FacilityId = f.FacilityId,
FacilityDescription = f.FacilityProductDescription,
FacilityCurrency = f.FacilityCurrencyId,
FacilityLimit = f.Limit,
ExpectedYear = d.ExpectedYear,
ExpectedMonth = d.ExpectedMonth,
ExpectedAmount = p == null ? 0 : (double)p.ExpectedAmount
}
);
I am trying to retrieve details from a Customer table that has a one-to-many relationship with a Facilities table. I am then trying to retrieve any details located in the ProjectedCashFlows
The problem I am having is that the query should return all Customer and Facilites information regardless of whether any values exist in the ProjectedCashFlows table.
Unfortunately this query is not doing that - it is only returning Customer and Facilities information when the Facility exists in the ProjectedCashFlows table.
I have used a MonthCalender table to list out each month in the year.
The relevant table information is:
Customers
CustomerCode
CustomerName
PrimaryArmId
Facilities
CustomerCode
FacilityId
FacilityCurrencyId
FaciliyLimit
FacilityDescription
ProjectedCashFlows
CustomerCode
FacilityId
ExpectedYear
ExpectedMonth
ExpectedAmount
ProjectedCashFlowStatusId
MonthsCalendar
ExpectedMonth
ExpectedYear
As an example I have a customer that has 4 rows in the Facilities table however, 2 of these facilities do not appear in the ProjectedCashFlows table so they are not being displayed.
If an entry doesn't exist in ProjectedCashFlows it should take the ExpectedMonth & ExpectedYear from the CalendarMonths table, return 0 for the ExpectedAmount and use the FacilityId from the Facilities table.
As you can probably work out I have just started to use LINQ.
Can anyone poke me in the right direction?
Your query uses p assuming it is non-null:
where d.ExpectedYear == currentYear
&& f.FacilityStatusId == 1
&& (p.ExpectedYear == null || d.ExpectedYear == p.ExpectedYear)
// etc
But you've used DefaultIfEmpty() which will logically create a sequence with a single null value when there are no ProjectedCashFlows.
So basically you need something like:
where d.ExpectedYear == currentYear
&& f.FacilityStatusId == 1
&& (p == null ||
((p.ExpectedYear == null || d.ExpectedYear == p.ExpectedYear)
// etc
))