Linq groupby with joining table - c#

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

Related

get left joined objects in join command in linq

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;

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 ?

Selecting Specific Child Records In Linq TO SQL C#

I have a table say Category with the following fields:
cat_id, cat_name and Cat_desc
I also have another table product with the following fields:
pro_id, cat_id, pro_name and pro_desc, is_finished
Ordinarily, if I select a category with Linq to sql, it returns the category with all the associated products.
But I want to select a category but the products returned should be only product with is_finished value that is true.
any suggestion/code sample will be appreciated.
You need to join the tables:
select * from product p
left join Category c on c.cat_id = p.cat_id
where c.cat_name = 'yourcategory' and p.is_finished = 1
In linq to SQL:
var query = from product in products
join category in categories on category.cat_id = product.cat_id
select new { product.is_finished = true, category.cat_name = "yourcategory" };
This is probably the wisest way to do what you're asking:
var query = from product in products
select new {
product,
finishedCategories = product.categories.Where(c => c.is_finished)
};
This creates an anonymous type that has the data you're looking for. Note that if you access .product.categories you'll still get all of that product's categories (lazily-loaded). But if you use .finishedCategories you'll just get the categories that were finished.

Linq Query to Get Distinct Records from Two Tables

I have two Tables - tblExpenses and tblCategories as follows
tblExpenses
ID (PK),
Place,
DateSpent,
CategoryID (FK)
tblCategory
ID (PK),
Name
I tried various LINQ approaches to get all distinct records from the above two tables but not with much success. I tried using UNION and DISTINCT but it didnt work.
The above two tables are defined in my Model section of my project which in turn will create tables in SQLite. I need to retrieve all the distinct records from both the tables to display values in gridview.
Kindly provide me some inputs to accomplish this task. I did some research to find answer to this question but nothing seemed close to what I wanted. Excuse me if I duplicated this question.
Here is the UNION, DISTINCT approaches I tried:
DISTINCT # ==> Gives me Repetitive values
(from exp in db.Table<tblExpenses >()
from cat in db.Table<tblCategory>()
select new { exp.Id, exp.CategoryId, exp.DateSpent, exp.Expense, exp.Place, cat.Name }).Distinct();
UNION # ==> Got an error while using UNION
I think union already does the distict when you join the two tables you can try somethin like
var query=(from c in db.tblExpenses select c).Concat(from c in
db.tblCategory select c).Distinct().ToList();
You will always get DISTINCT records, since you are selecting the tblExpenses.ID too. (Unless there are multiple categories with the same ID. But that of course would be really, really bad design.)
Remember, when making a JOIN in LINQ, both field names and data types should be the same. Is the field tblExpenses.CategoryID a nullable field?
If so, try this JOIN:
db.Table<tblExpenses>()
.Join(db.Table<tblCategory>(),
exp => new { exp.CategoryId },
cat => new { CategoryId = (int?)cat.ID },
(exp, cat) => new {
exp.Id,
exp.CategoryId,
exp.DateSpent,
exp.Expense,
exp.Place,
cat.Name
})
.Select(j => new {
j.Id,
j.CategoryId,
j.DateSpent,
j.Expense,
j.Place,
j.Name
});
You can try this queries:
A SELECT DISTINCT query like this:
SELECT DISTINCT Name FROM tblCategory INNER JOIN tblExpenses ON tblCategory.categoryID = tblExpenses.categoryID;
limits the results to unique values in the output field. The query results are not updateable.
or
A SELECT DISTINCTROW query like this:
SELECT DISTINCTROW Name FROM tblCategory INNER JOIN tblExpenses ON tblCategory.categoryID = tblExpenses.categoryID;<br/><br/>
looks at the entire underlying tables, not just the output fields, to find unique rows.
reference:http://www.fmsinc.com/microsoftaccess/query/distinct_vs_distinctrow/unique_values_records.asp

Joining tables in Entity Framework

I have a table called Students and a table called Majors, Students and Majors are joined by MajorId I have set this relationship already and have set the foreign key in the schema. When I access my Student object how can I return the MajorName column (this comes from the Majors table)? The only options I have in intellisense is Major_1, Major_1Reference, MajorId .
Major_1 should be a navigation property leading to the appropriate Major entry, so you should be able to access the Major's properties like this:
from s in ctx.Students
select s.Major_1.MajorName
You can use linq join statement like this to make query on the two tables...
var q = from s in Students
join m in Majors on s.MajorId equals m.MajorId
select new { m.MajorName };

Categories

Resources