Entity Framework Many to Many columns concept - c#

I've been used to this kind of convention before starting to work with Entity Framework/MVC:
tblMyItem (id, id_lookup1, val2, val3, val4...) - single, generic table
tblkLookup1 (id, val1, val2,...) - one to many relation table
tblmMyItemLookup2 (id, id_myitem, id_lookup2) - many to many relations table.
Recently I've found somewhere on the web that it's not good to create id column in tblmMyItemLookup2 when using Entity Framework, but I couldn't find more information on that. Could anyone please explain, why this is so significant?

When designing many-2-many relationship(i.e Student - Teacher) based on intermediate table (Student2Teacher) with only 2 foreign key columns, you'll end up having entities with navigation properties without intermediate table(no entity will be created for that table in context at all):
Student.Teachers <- EntityCollection<Teacher>
Teacher.Students <- EntityCollection<Student>
Meanwhile, if you add any extra field to your intermediate table, you'll have navigation properties pointing to intermediate entity:
Student.Student2Teacher
Teacher.Student2Teacher
making your querying uselessly more complex

In general we use lookup tables to macth associated records in two different tables that have a many to many relationship. For instance, let we have three tables: Students, Professors and StudentsProfessors. Since, a student can atten lesson that are serviced by many professors and a professor can teach more than one leasons then this is clearly a many to many relationship. So the lookup table called StudentsProfessors is used to match a student to her/his professors and vice versa. Now, the use of an id for each record of this lookup table is meaningless. We are not going to use this number anywhere. We just need to know that Student with studentId=10 is associated with professors with ids in (1,2,4,9). Just that and not the id of this record in the lookup table.

Related

What is the best database design for storing multiple subjects?

Recently I'm working on a project, in which I need save multiples subjects in my database, and numbers of subject will be change as per student's class. e.g: class "VII" has 6 subject (included 1 option subject), class "VIII" has 8 subjects (1 included option subject) and so on. Even the option subject can be different according to student's choice.
I'm using CheckedListBox control. Here is a screenshot.
I'm using MS Sql Server 2012. I'm facing difficulty to design database table. I can't understand should i create all the subject columns in my student table or ????(best way). Please help me, thanks in advance.
What you are describing is something that is called a Many to Many relationship. Many Classes have Many students.
You will have a students table, a subjects table and then a table student_subject table which links both the primary keys of the students and subjects table.
Reference: Many to Many
If a Student can have multiple Subjects, and a Subject can have multiple Students, then that's a many-to-many relationship. Which means there would need to be an intermediary table to link them.
Start with the tables for the objects themselves:
Student
----------
ID
Name
etc.
and
Subject
----------
ID
Name
etc.
Since these are independent aggregate root objects in the domain and neither one owns another one, their tables just contain information which describes that object. A Subject, for example, could have a name and a description, maybe a list of pre-requisites, etc.
Then you create the relationship table between them. A common practice is to just combine the names:
StudentSubject
----------
StudentID
SubjectID
If no two pairs of Student and Subject can be repeated, then the two foreign keys together can make the primary key. If they can be repeated (if the same Student can have the same Subject more than once) then you'd probably want to add a separate primary key to the table.
At its simplest, all this table does is create the relationships between the records in the main tables. However, this can potentially grow to be a domain entity in and of itself. If there are any attributes which describe the relationship between a Student and a Subject, those would be added to this table.
Your database schema should look something like this......
Students
Student_ID (PK)
Student_Name
etc .......
Subject
Subject_ID (PK)
Fee
etc......
Student_Subjects
Student_ID FK Students(Student_ID)
Subject_ID FK Subject(Subject_ID)
DateStarted
etc.....

Binding To a Composite FK

Is it possible/or good practice to have one table like an address book that is related to different entities e.g: People, Companies, etc
I am thinking of using a compsite FK (typeid = entity type id e.g: 1 for people, 2 for companies etc, while the other column refers to the pk of the entity's table).
The other alternative I have is to use a junction table between the entities and address book table.
I am using VS 2005 C#, and sql server 2008
Assumption: your entities are all stored in one table with a type discriminator
Yes, a foreign key can have multiple columns.
An address entry only needs to know the PK of the parent entity
It does not need to know the type of entity: entityType is an attribute of entity not address
Junction table or straight FK? It depends on your relationships:
Can one address be shared by more than one entity?
Can one entity have more then one address?
Yes to both: junction table
Yes to Q1 only: address PK is an attribute of entity. Entity is the child table in the FK
Yes to Q2 only: entity PK is an attribute of address. Address is the child table in the FK
And the case I would not expect:
No to both: 1:1 relationship or you need only one table, address is an attribute of entity
I see no need for a type and an entity_id that refers to one table or the other. This is a complicated approach (two tables using the same ID pool and no foreign key to a table possible) that might cause problems later.
Your problem seems so simple that no tricks should be needed here.
You have companies, persons and addresses. If each person and each company has one address, you have the address id in the companies and persons tables. If a person can have more than one address you need a bridge table. Same for more than one address per company. That's all.

Implement a "One-to-many" relationship with DataSets

I have two tables, one containing patient information, the other, the notes for each patient.
(One patient, many notes for a patient).
Given this, in the Designer (which you access by right-clicking on the chosen DataSet), how do I create a one-to-many relationship? I have never performed this before.
Secondly, for the patient notes table, how would I add a note to a patient record using SQL syntax? Note, this is not updating an existing one, but adding a completely new one to the patientNotes table using the unique patient ID number as the reference (so only that specific patient has that note added to them, not them and everyone else).
Very technically speaking, you don't need to do anything to create a one-to-many relationship. You just have to have the two tables set up as you have them and use them as you intend on using them. I work in data warehousing and unfortunately a great many of our relationships like this are not formalized with any sort of key or constraint.
The correct way to do it is to implement a foreign key constraint on the patient ID column on the patientNotes table. A FK will only allow you to insert data into patientNotes IF the patient ID exists in the patient table. If you would try to insert a note into your table that has a patient ID that doesn't exist in the patient table, the insert would fail and the SQL engine would give you an error. Note that the column on the patients table that you are creating the FK to must be a primary key.
Inserting data will really go as any other insert would:
INSERT INTO dbo.patientNotes (patientId, NoteText)
VALUES(4265, 'During his 8/14/2014 visit, Mr. Cottinsworth complained of chest pains. Evidently he has been wearing a lady''s corset to hide his large gut. Advised the very portly Mr. Cottinsworth to discontinue corset use'
You could toss that in a SP, put it in your code and use parameters for the patientId and NoteText, however you wanted to do it.
As far as doing this all in Visual Studio graphically, I can't be of much help there. I typically use the TSQL editor and type out what I want to do to the DB. I'm sure there are tutorials abound on how to set up FKs on Visual Studio.
Further reading:
http://msdn.microsoft.com/en-us/library/ms189049.aspx
http://www.scarydba.com/2010/11/22/do-foreign-key-constraints-help-performance/
what are the advantages of defining a foreign key

A Recipe Database Model Advice

I'm trying to design a snackbar automation system (to answer the first question - No, it's not a homework, it's for learning purposes) and I have an issue with with the recipes and how to present them in the database. I have two options:
Option 1:
[Ingredients] -> [IngrID, IngrName]
[Recipe] -> [RecipeID, RecipeName]
[IngRecipe] -> [IngrID, RecipeID]
In this case the third table is a typical many-to-many table, the model looks correct and it's a piece of cake to manipulate with the data using Entity Framework. But I want to keep track of the amounts as well. Generally I use Ingredients as a table to insert the new purcheses. If the ingredient exist, just update the amount.
Option 2
Now if I add column "amount" as a column to IngRecipe, the whole idea of many-to-many table vanishes and I no longer can use the entity model to fill the fields automatically. But I can't seem to find a more apropriete place for this column. Where and how will I say "Well, get me 100 gr of chicken breast and add it to whatever recipe"
Any help is appreciated. Thanks in advance!
It's a solid model start, consider:
RecipieIngredients -> Recipe (FK), Ingredient (FK), IngredientQuantity
Key over (Recipe, Ingredient)
Note that it is still a M-M relationship (the quantity is not part of the PK nor involved in a FK), just with more relevant data for this relationship pair. The names can be changed, but at some point, this must be represented as a M-M relationship in a normalized relational model.
Don't let the framework ruin a good normalized design - and I hope EF can cope with such trivial scenarios; even LINQ2SQL can.

Self Referential Entity - MANY TO MANY

Just after some advice regarding this database design situation.
So I have two tables in the database.
Table 1: Patients
Table 2: Claimants
Patients holds attributes data on a private patient, so details about the person, his/her birthday, names, medical conditions, etc etc..
Claimants is the entity who pays on behalf of the patient, so Claimant can be a patient himself, another person, a business (who pays for work injury), private healthcare provider, government bodies etc etc..
Patients and claimants have IDs who are foreign keys in other tables such as invoices, receipts etc...
One Patient can have multiple Claimants (More than one entity can pay on his behalf), each Claimant can have multiple patients.
On further investigation, I've identified that many of the attributes of Patients and Claimants overlap as a Patient can pay for himself thus is a private Claimant.
My thinking is to merge the two tables into one and simply call it accounts and have a claimantType field to identify the type of the account, be it private, healthcare, business or government.
What potential practical drawbacks do I need to keep in mind with this change? Apart from the changing the other linked tables in database?
EDIT: Just to make it clear, There's already a junctional table PatientClaimants which basically just map the patients to the claimants. Thanks!
Merging these two tables I believe is wrong.
A patient is always a human. So it cannot be a business or an organisation.
I believe here you have:
Address
=======
......
Person
=======
AddressId (FK)
BusinessEntity
==============
AddressId (FK)
Patient
=======
PersonId (FK)
Claimant
========
PersonId (FK)
BusinessEntityId (FK)
Here PersonId or BusinessId one of them can be null.
You could either (a) put in an intersection table that relates patient IDs to claimant IDs, or (b) as you discussed, merge them together - but if you already have data out there that could be problematic.
You could also set up a demographics table that shows common data between patients and claimants and references an abbreviated patient/claimant table - this way you do not break your existing structure.

Categories