Linq to SQL, many to many design - c#

I'm trying to take an object and design an SQL table to store it. The object has a member called "Roles" which is an enum that has 4 values. Each object can have several different roles.
Right now, I've taken the enum and created an eponymously named SQL table out of it and added the 4 roles to it. Now I'm trying to design the object table and I can't figure out how to get the many to many relationship working for it. I would also like it to work well with Linq-to-SQL. It would be nice to have the enum preserved, but if not an array of strings could also work.
In short, I need a table that has a many-to-many between Roles and Object.Roles (or Object.Roles[])
Thanks!

Generally, Many-To-Many relationships in Linq2SQL (and Entity Framework) are created by introducing an association table, with only the primary keys from the two tables you want to link, and where each row corresponds to an association.
Since your Role and Object.Role could be difficult to keep apart in an attempt to explain this, I'll give another example: in a school, each teacher can have many students, and each student can have many teachers. The table structure to represent this would then be
Teachers Students StudentTeacherRelations
******** ******** ***********************
TeacherId StudentId TeacherId
FirstName FirstName StudentId
etc... etc...
Now, Linq2SQL and EF are both smart enough to recognize this as a many-to-many relationship, and introduce navigation properties in your model. A POCO with appropriate properties for the Student object could look like this:
public class Student
{
public int StudentId { get; set; }
public string FirstName { get; set; }
// etc
public IEnumerable<Teacher> Teachers { get; }
}
If this is set up correctly, the O/R mapper will automatically populate the Teachers property.
Update: In response to comments, here is a how I'd structure the rest of the database if I wanted to include a scenario where each teacher can give some students homework consisting of a number of questions:
HomeworkAssignments Questions Answers
******************* ********* *******
HomeworkAssignmentId (pk) QuestionId (pk) AnswerId (pk)
... HomeworkAssignmentId (fk) QuestionId (fk)
... StudentId (fk)
...
StudentHomeworkAssignmentRelations TeacherHomeworkAssignmentRelations
********************************** **********************************
StudentId (fk) Teacherid (fk)
HomeworkAssignmentId (fk) HomeworkAssignmentId (fk)
As you can see, there's quite a lot of tables here. However, this structure allows you to let each teacher create many homework assignments, and then hand each assignment out to a number of students. You'll have a navigational property Student.HomeworkAssignments of type IEnumerable<HomeworkAssignment>, via which you can find all the questions a student has to answer. For each posted answer, you store a row in the Answers table, which is linked to both questions and students by 1-to-many relations - each answer can belong to one question only, and be given by one student only.
The key here is that you don't need to be able to access each answer given by a student directly - in both Linq2SQL and EF it's possible to request data from many tables at once in various ways. One of those ways is
var answersToTheLastExam = context.Students
.SelectMany(s => s.HomeworkAssignments)
.OrderBy(ha => ha.Date) // this might need modifying to get the last one first
.First(ha => ha.Questions.Count() > 0)
.SelectMany(ha => ha.Questions)
.SelectMany(q => q.Answers)
.Where(a => a.StudentId == myId)
Note that this code is untested an might not work as I say it will. I'm just trying my best off the top of my head here =)

Roles
Id Pk
ObjectRoles
Id Pk
ObjectRoleRoles
RolesId Pk & FK
ObjectRolesId PK & FK
var result = (from orr in _context.ObjectRoleRoles
inner join r in _context.Roles on orr.RolesId equals r.Id
inner join or in _context.ObjectRoles on orr.ObjectRolesId equals or.Id
where orr.RolesId equals 1
select r).ToList();
The fields in ObjectRoleRoles must be both the PK and FK.

Related

Having an entity possess multiple one to one relationships? Entity Framework

Does having a child with multiple one to one parents in a parent table make sense? Or would there be a more advantageous way to configure the relationship?
Ef core details:
Say I have a ProductSales table already, and I'd like to have a separate table that has a one to one with 2 ProductSales (for aggregating and comparing 2 product sales).
ProductSales
StoreId PK
ProductId PK
Date PK
SalesAmount
DailyChange
StoreId PK, FK1
ProductId PK, FK2
First Date FK1
Second Date FK2
AmmountDifference
Each ProductSales row will only be referenced once in the DailyChange table.
Does it make sense to have 2 one to one relationships between these 2 tables?
DailyChange --------- ProductSales1
DailyChange --------- ProductSales2
Daily Change builder:
builder.HasOne(b=> b.InitialProductSales)
.WithOne()
.HasForeignKey<DailyChange>(b => new { b.StoreId, b.ProductId, b.Date});
(and a similar one for the end date)

If one table can provide the info we need, do I need to join another table

I have two tables, table1 has a foreign key of table2. I want to get some info from table1 including a column which both table1 and table2 have. Should I join these two table to get the info?
For example:
I have two tables Course and Student, such as below
enter image description here
Solution1:
Course
|project CourseId, CouseName, StudentName, StudentId
Solution2:
Course
| project CourseId, CourseName, StudentName
| join Student
on $left.StudentId == $right.StudentId
| project CourseId, CourseName, StudentName
To get the CourseId, CourseName and StudentName, which solution is correct? Is it a good practice to pick solution2?
Please ignore the table design. It is just an example. The issue is coming from a real project that we need a query from one table which contains a foreign id and common column from other table. The query should give the common column back. Is it necessary that join the second table to get the common column?
Course table should not have Student name, it’s redundant data. And yes you can use inner join or left join on student id. Just bear in mind with the given information provided by you, the case where student id can be or cannot be null in course table.
I believe the concept of join should only be used when we need data from 2 or more tables. If you have all the required data in a single table, why you need a join. If were you, I will surely move forward with first solution. Thanks
Your tables do not follow those three normalization forms.
This is how entities and relationships should be organized if we are talking about the common scenario of designing a database for a school or something something similar to this.
There is a Many to Many relationship between Courses and Students, which allows us to associate N students with one course, and M courses with one student (one course can be attended by many students, and one student can attend many courses).
Also, this design follows the 3rd Normalization Form.
Learn more about normalization forms
Learn more about Many to Many relationships

GetAysnc by Id from many to many Entity Framework

I have 2 tables Center (centerId, name, address,...) and Student (StudentId, NAme, Address) and I determined they have a many-to-many relationship. As a result, I have created a new table CenterStudent (centerId, studentId,...) to join these 2 tables, and I set both centerId, studentId is PK and FK, and cascade delete.
Now I want to get all records with the same studentId. So I wrote
var lists = await studentCenterService.GetAsync(cancellationToken, studentId);
But I get an error
Entity type 'UserCenter' is defined with a 2-part composite key, but 1 values were passed to the 'DbSet.Find' method.
Could anyone give me a solution?
The error seems pretty clear - the .Find() method in EF works only on the complete PK - so if you have a PK made up from two columns (centerId, studentId), you cannot use .Find() to find all entries if you only supply studentId.
You need to use a
UserCenter.Where(x => x.studentId == studentId)
approach instead.

adding object entity framework using many to many relationship

I have a database like lets say a class Student and a class Course. These two have many to many relationship through a join table, holding ids of these two tables which is hidden in EF the way it supposed to.
First if I add two courses to a student. Like
John.classes.Add(math); John.classes.Add(physics) where 'John', math and physics are objects of their respective classes. When i save changes, everything happens the ways it should happen. An entry in students table, two entries in courses table and two entries in StudentCourses join table. All good.
But then, when i add another student say 'Bob' with same two classes. Bob.classes.Add(math); Bob.classes.Add(physics);It should add a row in students table adding Bob and two rows in StudentCourses join table. This doesn't happen. A row is added to students table but no rows are being added to StudentCourses table giving error of duplicate entry in courses table. Entity Framework is not adding courses because math and physics already exist in courses table but it should add two entries in StudentCourses join table.
A work around this is by adding an id column in join table and use this table as normal table and manually add entries in StudentCourses table. But i dont want to do this, I want to know the actual solution.
Thanks
i solved it by
team ct = context.teams.Find(club.id);
if (ct == null)
{ comp.teams.Add(club); }
else
{ ct.competitions.Add(comp); }
context.SaveChanges();
where comp is competition object.
I am sure this is not the actual solution but just a way around. This can't be...

insert a row in a table that links with PK autoincrement of another table

I have two tables
contact table
contactID (PK auto increment)
FirstName
LastName
Address
etc..
Patient table
PatientID
contactID (FK)
How can I add the contact info for Patient first, then link that contactID to Patient table
when the contactID is autoincrement (therefore not known until after the row is created)
I also have other tables
-Doctor, nurse etc
that also links to contact table..
Teacher table
TeacherID
contactID (FK)
So therefore all the contact details are located in one table.
Is this a good database design?
or is it better to put contact info for each entity in it's own table..
So like this..
Patient table
PatientID (PK auto increment)
FirstName
LastName
Address
Doctor table
DoctorID (PK auto increment)
FirstName
LastName
Address
In terms of programming, it is easier to just have one insert statement.
eg.
INSERT INTO Patient VALUES(Id, #Firstname,#lastname, #Address)
But I do like the contact table separated (since it normalize the data) but then it has issue with not knowing what the contactID is until after it is inserted, and also probably needing to do two insert statements (which I am not sure how to do)
=======
Reply to EDIT 4
With the login table, would you still have a userid(int PK) column?
E.g
Login table
UserId (int PK), Username, Password..
Username should be unique
You must first create the Contact and then once you know its primary key then create the Patient and reference the contact with the PK you now know. Or if the FK in the Patient table is nullable you can create the Patient first with NULL as the ContactId, create the contact and then update the Patient but I wouldn't do it like this.
The idea of foreign key constraints is that the row being referenced MUST exist therefore the row being referenced must exist BEFORE the row referencing it.
If you really need to be able to have the same Contact for multiple Patients then I think it's good db design. If the relationship is actually one-to-one, then you don't need to separate them into two tables. Given your examples, it might be that what you need is a Person table where you can put all the common properties of Doctors, Teachers and Patients.
EDIT:
I think it's inheritance what you are really after. There are few styles of implementing inheritance in relational db but here's one example.
Person database design
PersonId in Nurse and Doctor are foreign keys referencing Person table but they are also the primary keys of those tables.
To insert a Nurse-row, you could do like this (SQL Server):
INSERT INTO Person(FirstName) VALUES('Test nurse')
GO
INSERT INTO Nurse(PersonId, IsRegistered) VALUES(SCOPE_IDENTITY(), 1)
GO
EDIT2:
Google reveals that SCOPE_IDENTITY() equivalent in mysql is LAST_INSERT_ID() [mysql doc]
EDIT3:
I wouldn't separate doctors and nurses into their own tables so that columns are duplicated. Doing a select without inner joins would probably be more efficient but performance shouldn't be the only criteria especially if the performance difference isn't that notable. There will many occasions when you just need the common person data so you don't always have to do the joins anyway. Having each person in the same table gives the possibility to look for a person in a single table. Having common properties in a single table also allows you have to have doctor who is also a patient without duplicating any data. Later, if you want to have more common attributes, you'd need to add them to each "derived" table too and I will assure you that one day you or someone else forgets to add the properties in one of the tables.
If for some reason you are still worried about performance and are willing to sacrifice normalization to gain performance, another possibility is to have all person columns in the same table and maybe have a type column there to distinguish them and just have a lot of null columns, so that all the nurse columns are null for doctors and so on. You can read about inheritance implementation strategies to get an idea of even though you aren't using Entity Framework.
EDIT4:
Even if you don't have any nurse-specific columns at the moment, I would still create a table for them if it's even slightly possible that there will be in the future. Doing an inner join is a pretty good way to find the nurses or you could do it in the WHERE-clause (there a probably a billion ways to do this). You could have type column in the Person table but that would prevent the same person being a doctor and a patient at the same time. Also in my opinion separate tables is more "strict" and more clear for (future) developers.
I would probably make PersonId nullable in the User table since you might have users that are not actual people in the organization. For example administrators or similar service users. Think about in terms of real world entities (forget about foreign keys and nullables), is every user absolutely part of the organization? But all this is up to you and the requirements of the software. Database design should begin with an entity relationship design where you figure out the real world relationships without considering how they will be mapped to a relational database. This helps you to figure out what the actual requirements are.

Categories

Resources