get left joined objects in join command in linq - c#

I have 2 classes for examle:StudentClass and SelectedLessonClass.
StudentClass{
studentId,
name,
family}
SelectedLessonClass{
studentId,
lessonId}
I need information of students that select lesson with lessonId=12;
I use join command:
students=students.join(selectedLessons.where(sl=>sl.lessonId==12).tolist(),st=>st.studentId,sl=>sl.studentId,.....)
Please Guide me,what things must I fill instead of ..... ?
Thanks

Let say you have listStudents and listLessons you can try something like this (result is the list of students that match your criteria):
var result = from s in listStudents
join l in listLessons
on s.studentId equals l.studentId
where l.lessonId=12
select s;

Related

Linq groupby with joining table

Let's suppose there is a database to manage students.
I'm using the following (simplified) classes:
Student
int id
string name
StudentEnrollmentInfo
int studentId
int courseId
Course
int courseInfo
string name
In the aforementioned tables, studentenrollmentinfo is a joining table, to handle the many to many relation between courses and students.
Now I'd like to query the names of all students who are currently enrolled in a list of different courses. For example:
Get all students enrolled in Biology, Maths and Arts, I'd like to get all students that are enrolled in ALL of those classes.
I have tried the following:
List<string> requiredCourses = new List<string>(){"Maths", "Biology", "Arts"};
var query = from student in _context.students
join enrollmentInfo in _context.StudentEnrollmentInfo on
student.id equals enrollmentInfo.studentId
join course in _context.Course on course.id equals enrollmentInfo.courseId
where requiredCourses.All(r => r.equals(course.name))
select(student.name)
This however does not work, my guess is because the joins, in addition to the joining table flattens the list, making it where every student with every course combination is a unique value, making it so that there is never any AND condition that is true.
Can anyone suggest something to point me in the right direction?
List requiredCourses = new List() { "Maths", "Biology", "Arts" };
var query = (from student in _context.students
join enrollmentInfo in _context.StudentEnrollmentInfo on student.id equals enrollmentInfo.studentId
join course in _context.Course on course.id equals enrollmentInfo.courseId
where **requiredCourses.Contains(course.name)**
select student.name).Distinct().ToList()
hope it will solve your purpose. distinct will help for your unique data

.NET SQL Query joining two different tables

I'm brand new to .net MVC, and while I have some basic experience with writing SQL queries, I'm not sure how to go about what I need to do for .NET.
My initial query looks like this:
var results = (from s in db.Members
join sa in db.FocusArea on s.ID equals sa.MemberID
where sa.Area == SearchString
select new { s.ID, s.Name, s.Overview }).ToList();
This is not functioning correctly. It is seaching in the s.Overview for some reason. And, I need to make this query much more complicated. In short, I have three tables I need to search across. And with this query, it is not working:
var conceptResults = (from s in db.Cohorts
join oa in db.OutcomeArea on s.ID equals oa.CohortID
where ((oa.Area.Contains(SearchString))
|| (oa.OutcomeType.Contains(SearchString)))
select new { s.ID, s.Name, s.Overview }).ToList();
I need to use my SearchString to search for matches in both Area and Description in db.FocusArea.
I also need to use my SearchString to search for matches (contains) in another table db.SpecificFocusAreas for column SFocusArea where again the join is the ID/MemberID.
Is there a way to essentially do a join or join type of statement? I don't want to join all three tables because I am looking for results from either of the two joins, not from all joins.

Selecting a new object without grouping in linq?

I am trying to write a query to collect the Job number, start date, customer name, Model, and completion date for jobs at my work. To get this info, I look at 3 different tables, using joins to put them together. Here are the three tables:
STAGE - (stages each job goes through during production)
ORDER - (this is where I get the customer's name)
JOBS (start date, completion date, job number, model)
So most of the info is from the JOBS table. But I'm joining onto the ORDER table by Job Number (JobNum) to obtain the customer's name. Here's what the query looks like. I created it in SQL before I tried to translate it into one of my ViewModels:
var CompletedTrucksQuery =
(from FA in context.JOBS
join ORD in context.ORDER on FA.ORGANIZATION_ID equals ORD.ORGANIZATION_ID
where FA.ORDER_NUMBER == ORD.ORDER_NUMBER
join StageF in context.STAGE on FA.JobNum equals StageF.JobNum
where StageF.StageID == 325
join TruckComp in context.STAGE on FA.JobNum equals TruckComp.JobNum
where TruckComp.StageID == 327
join INSP in context.STAGE on FA.JobNum equals INSP.JobNum
where INSP.StageID == 487
orderby StageF.CompDate descending, FA.JobNum ascending
select new {FA.JobNum, FA.StartDate, ORD.CUSTOMER_NAME, FA.MODEL_NAME, StageF.CompDate});
At this point, I'm wanting to select the
Job number (from JOBS),
the start date, (From JOBS),
the Customer's name (from ORDER),
the Model of product (from JOBS),
and the date it was completed in StageF (from STAGE)
as you can see in my select statement. I DO have an object to hold each of these called CompJob, and have tried to do a 'group by' and select a new CompJob and set the properties, but I can't seem to group it right and get 'access' to all of the properties I want to set. Here's an excerpt of what I'm talking about:
group new {FA.JobNum, O = ORD} by StageF into grp
select new CompletedTruck
{
JobNum = grp.Key.JobNum,
StartDate = grp. //???
}
As you can tell I stopped, because for some reason I couldn't 'find' the start date. I know it's something to do with my grouping. I'm very new to linq and databases, in general.
MY QUESTION: What's the best way I can select these columns of interest into my
ObservableCollection<CompJob> CompJobList;
so that I may use it in my scrollviewer in a view?
Thanks to everyone for helping me out. I solved the issue and this is what I did. I followed Gert Arnold's suggestion of selecting a new CompJob object. This would set each row of the query to a new object:
select new CompJob {JobNum = FA.JobNum, StartDate = FA.StartDate, Customer = ORD.CUSTOMER_NAME,.....}
and then said
).ToList();
At the end of the query. Then I set my ObservableCollection to the list returned by my query:
CompJobList = CompletedTrucksQuery ;
Thanks again for helping me out; I know I'm new to all of this!

Data extraction from a SQL database

I need some help with an extraction method. I am currently working on a school card project and I need to extract all students learning in certain teachers class. I have table named Teachers, table named Classes and a table named Students. I want by given Teacher ID to receive all the students in his/her class.
Table Teachers contains TeacherID, Name, and so on.
Classes contains TeacherID, StudentID.
Students contains StudentID and FirstName, LastName.
My problem is that I want to return a whole list of students and I am not quite sure how to do it and what type I should be using. Could you please assist me ?
The code so far
var studentID = from t in context.Teachers
join s in context.Classes on t.TeacherID equals s.TeacherID
join stu in context.Students on s.StudentID equals stu.StudentID
select stu.FirstName
.SelectMany();
As you can see the use of .SelectMany() is wrong and thus I do not seem to be able to replace it with anything so far. Also, since there are many names the use of var is incorrect, I suppose.
how about this..
var studentID = from t in context.Teachers
join s in context.Classes on t.TeacherID equals s.TeacherID
join stu in context.Students on s.StudentID equals stu.StudentID
WHERE stu.FirstName == FirstName
select t;
I would do it on something more unique what if you have 5 Thomas's ?

SQL: Count rows which are not present in table

I got two tables called: EmployeeTable & TaskAssignmentTable.
They look like this :
TaskAssignmentTable shows tasks assigned to employees. In order to assign new tasks to employees i want to have count of tasks assigned to different people and then assign task to people who have least tasks assigned.
Problem: using normal count() on TaskAssignmentTable results in this table:
But what i want is some sort of join between tables which shows count of rows which are present in first table and absent in 2nd table with count equal to 0 like this one:
So what would be the SQL query to join tables and do such thing? (Optional: Since I'm using C# Linq-2-SQL i would be grateful if someone can write LINQ syntax for this).
You need a LEFT OUTER JOIN based upon your statement that you want rows that are present in the first table but not the second:
SELECT EmployeeID, Name, Count(TaskID) as CNT
FROM EmployeeTable e
LEFT JOIN TaskAssignmentTable t
ON e.employeeID = t.FKEmployeeID
GROUP BY EmployeeID, Name
Try
SELECT EmployeeID, Name, Count(TaskID) as CNT
FROM EmployeeTable emp
LEFT JOIN TaskAssignmentTable task on emp.employeeID = task.FKEmployeeID
GROUP BY EmployeeID, Name
For that you have to use Left Outer Join.
SELECT EmployeeID, Name, Count(TaskID) as CNT
FROM EmployeeTable emp
LEFT OUTER JOIN TaskAssignmentTable task on emp.employeeID = task.FKEmployeeID
GROUP BY EmployeeID, Name
And LINQ Version of this query look like this
var employees = from emp in dbContext.Employees
join task in dbContext.TaskAssignmentTable
on emp.employeeID equals task.FKEmployeeID
into tEmpWithTask
from tEmp in tEmpWithTask.DefaultIfEmpty()
group tEmp by new { emp.EmployeeID, emp.Name } into grp
select new {
grp.Key.EmployeeID,
grp.Key.Name,
grp.Count(t=>t.TaskID != null)
};
You need to OUTER JOIN the two table (in your case a LEFT JOIN):
SELECT EmployeeID, Name, Count(TaskID) as CNT
FROM EmployeeTable emp
LEFT JOIN TaskAssignmentTable task on emp.employeeID = task.FKEmployeeID
GROUP BY EmployeeID, Name

Categories

Resources