What will be the DB Context code for executing this SQL? - asp.net-mvc

I am new to DbContext and I am confused about how to join tables using DbContext - can someone tell me the code equivalent to this SQL?
Select *
From AssignedCourses
Join Students On StudentRollnumber = Students.StudentRollno
Join Courses On Courses.CourseId = AssignedCourses.AssignedCourseId

With EF you don't seldom need joins. Provided your relations are setup right in your backend, tools generate the models for you using navigational properties. Even without tools, it is easy to create models with navigatinal properties. That query could be written in different ways depending on your real needs. With navigational properties, generally you don't have the middle bridging table, but directly reference to Courses from Student (courses that a student is enrolled) or Students from Course (Students that are enrolled to that course). Assuming you want primarily the Students and the Courses they were enrolled to:
var result = ctx.Students;
// or preload them the Courses as well
var result = ctx.Students.Include(s => s.Courses);

you can use LINQ query :
from ac in db.AssignedCourses join s in Students on StudentRollnumber equals s.StudentRollno join c in Courses on c.CourseId equals ac.AssignedCourseId

Related

Can't use my joining table from DbContext

I have database with different tables. But I can't get access to some tables, and I'm curious why? For example, there is Projects table and Users table in database, and I need to get list of all users that are in specific Project by Id. These tables have many to many relationship, so there is joining table with ProjectId and UserId. It's logic to use some Join to get users that I need from table Users with help of this joining table from db. But how can I make Join when my DbContext doesn't have joining table? How can I get access to joining table using DbContext, or maybe there are some different ways to get list of users by project id?
If someone have similar problem, here is a simple way to use all the data from collections in model
var project = _db.Projects.Include(x => x.Tickets).ThenInclude(y => y.Users).SingleOrDefault(p => p.Id == id);
so after that you gonna have your model and all the data from collections that you need
ProjectUser - is joining table, use for link two tables. This tables must have (usually) Collection for access to this many-to-many data.
So you can will have collection of users for this project. And doing filtering by users from your Ticket (example from image).
Yes, exists few different ways - setting with ef fluent, or attribute, or dbcontext. Better to find complete guide for many-to-many setting in your application.

How to retrieve all of one table and all joined records in another with the other table's columns in ActiveRecord

I would like to retrieve all of one table and all joined records in another.
I would like to have all columns from both tables
This is extremely simple in SQL
e.g.
SELECT *
FROM students
JOIN teachers
ON students.id = teachers.student_id
How can I do the same in rails?
I've tried variations on
Student.includes(:teacher)
and
Student.joins(:teacher).includes(:teacher)
The join is working, but I cannot access columns from Teacher table
Note that the end goal is simply to be able to create an instance variable in the controller so that I can access both student and teacher data in the view
Student.includes(:teacher) will return ActiveRecord::CollectionProxy which means if take particular object in this collection, it will be Student class object.
Unlike sql query fired and returning data from 2 tables, it does not work same in rails, you get data only from students column which will relate associated record in teachers table because it represent Student model.
You can access further teachers data like,
students = Student.includes(:teacher)
students.last.teacher.name
In above no new query will get fired in database when you call teacher association on object

Entity Framework - when/why do I need to model a "link" table?

I will preface it by saying I'm a database person, moving into .NET, MVC, EF etc. So I fully understand about joins and foreign keys and so on but I am struggling with the EF side.
I worked through a tutorial where we did the following:
create a Student table (StudentID and personal details), a Course table (CourseID and subject details), and an Enrollment table (EnrollmentID, student and course IDs and the grade given to that student for that class).
create Models, Controllers and Views for Student and Enrollment entities to allow editing the name of a Student, enrolling a student for a class and giving them a grade, list out all enrollments, etc.
In that tutorial the Enrollments table is (what I know as) a "bridge" table because student to class is a many-to-many relationship.
So do I only need this "intermediate" model/view/controller if it's a many-to-many scenario like this?
The actual structure I want to program is:
Article (ArticleID, title, author, summary, content...) is a member of a
Category (CategoryID, title, description, ...)
Then I want to have a drop down list (or whatever UI element) of Categories of which clicking on the selected Category will give a page with a table of Title/Author/Summary of the articles that go in that category.
If an Article can be in more than one category ("Effective Use of Catnip" could be under both "Playing Games with Cats" and "Life Hacks") is that where I would need a 'bridge' table?
Please can someone explain in simple terms - whether I am just being put off by the "many to many" nature of the data in that tutorial, or if the 'bridge' table structure is more fundamental to EF for navigating a PK/FK relationship.
I think the tutorial you are reading is trying to introduce you to the basic concepts of EF. If you have a many-to-many relationship, on database side you will always have three tables:
Student
Course
Enrollment (Student_Id, Course_Id)
On EF world, you can represent those three tables as three different entities. However, if you want to have a more "natural" way of representing the relation between Students and Courses, EF allows you to declare many-to-many as two lists:
public class Student {
... properties
virtual List<Course> Courses;
}
public class Course {
... properties
virtual List<Student> Students;
}
However, you need to instruct EF how this references on both side needs to be treated. For that, you can use fluent API. With this fluent API you can define the table name that references both tables/entities:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasMany<Course>(s => s.Courses)
.WithMany(c => c.Students)
.Map(cs =>
{
cs.MapLeftKey("StudentRefId");
cs.MapRightKey("CourseRefId");
cs.ToTable("StudentCourse");
});
}
Check this article explaining the M:N relationship using fluent library API. Is really simple, and with that you don't need this additional element on the middle.
In terms of UI, you just need to select the list of courses the student want to take, or the list of students the course has to have. Is up to you how you want to present the information to the user, as both functionalities (students taking courses and courses defining its students) point to the same m:n relation.
I think a simple way can be to show a </select> list with the students, and then show the list of courses he can apply to.
The project you want to create uses the same ideas. Basically, with EF you will always need to think in terms of "tables". It is true that EF allows you to abstract your tables to entities, but still you need to follow some rules. To sum up: you are right. The "bridge" table is where you need to store the many-to-many relationships.

Grails' implementation of bidirectional one-to-one relationship at the database level

I've two domain classes which are bonded with a bidirectional one-to-one relationship to each other, this being implemented using hasOne.
class AssessmentData {
static hasOne = [assessmentField:AssessmentField, assessment:Assessment]
AssessmentField field
}
class Assessment {
AssessmentData assessmentData
}
But I'm quite a bit confused about the way Grails implements this relationship at the database level. As described here, it simply sets the foreign key at the child domain class only, in my case, to the Assessment and AssessmentField tables. Its my primitive instinct that both tables should have a foreign key referring to each other in order to establish a one-to-one bidirectional relationship. But since this is not the case, I wanna know how this is achieved by Grails.
Its my primitive instinct that both tables should have a foreign key referring to each other in order to establish a one-to-one bidirectional relationship
Your instincts have failed you. The domain described in your question will generate these 2 database tables:
assessment_data
----------------
id
assessment
----------------
id
assessment_data_id
Using SQL we can get the assessment associated with an assessment_data with id 4
select * from assessment where assessment_data_id = 4
We can also go the other way and get the assessment_data associated with an assessment with id 5 using
select ad.* from assessment_data ad
inner join assessment a ON a.assessment_data_id = ad.id
where a.id = 5
So if we can "go both ways" in SQL, then we can do it with HQL, criteria queries, dynamic finders, etc. because these all ultimately get translated to SQL.

How to layout tables and relationships for MVC project

So I am working on an MVC project to put to work the studying I have been doing. I am wrestling with the concept of Database Table relationships and foreign keys. I am working on a simple ecommerce site (displays products, shopping cart, user accounts..etc).
I have the following tables to start out with:
1) Products
2) Categories
I setup the Products and Categories tables to have a ProductId and CategoryId respectively. In my MySQL db, I created a FK on the Products Table to relate to the CategoryId field on the Categories table (I am not sure this was correct to begin).
My expectations for the way the database would handle the table relationship: I didn't want the DB to do anything with the products table if I deleted a category out of the Categories table, or vise versa. The only thing would be that the category field in a Product would be blank (or default) if their category was removed.
Finally, do I have to do anything in my entity classes such as in the Products class, add the ProductId to the Category.ProductId?
Eventually, when I Orders and Users to the project, I can see a relationship where each user -> many orders -> each order has many products -> and each product is in one category.
But I am having a hard time understanding how or if I should be setting up a Foreign key relationship in the two current tables of Products and Categories and if so how to setup my entity class in relation to that FK.
Any advice.
It has been my experience (with L2S) that you don't want to specify any relationships between tables. I have simply done the PK, FK logic myself. This keeps the L2S generated objects simple and is most likely the way you worked with them before in SQL. That, at least, is the case for me.

Resources