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

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

Related

Winforms with SQL Server : Define relations in SQL

When I write C# applications, I use to write sql relations as inner join for example, in the query:
select xxx from TableA as A inner join TableB...
I don't really see why I should define these realtions (hard defined) in Management Studio.
Should I, and why if required?
Regards
Two main reasons and a minor third one: data-integrity and performance - and documentation.
Performance is simple: if you define a relationship between two tables you will normally automatically create an index on those two columns, and your database will use those indexes to speed up look-ups when they can be used.
As for data-integrity, even though you leave the important part of your join out of your example, you assume in a join that a foreign key field can only contain values that exist in the primary key field. Your database can make sure of that, and will make sure of that when you define those relations in SQL server.
If you do not define those relationships, you could easily create a situation where you have, say, Orders, that belong to Customer 12345, who does not exist in your Customer table.
Or you could delete Customer 23456, leaving all their Orders in your system, but without an existing Customer.
A final reason is documentation: your database is not only made to be accessed by your code. If someone else accesses your database and sees only unconnected unrelated tables, how will they know that field cstID in table CstOrderHdr happens to be a reference to field id in table Relations where Relation.RelTyp = 'Customer'? Who is to stop them from filling in 0, null or a random number?

The table does not have a primary key defined error

I have two tables that are basically link tables.
So one looks like this;
QueueId
TaskId
the two columns link to a Queues table and a Tasks table.
There is no primary key and i don't believe I need one.
I so try to import it into my .EDMX and I get the warning that
the table does not have a primary key defined but that it's been inferred as a read only table.
Also, the table doesn't show up in the Diagram and there is no model created for it.
I added a primary key and then got errors in my code.
I deleted all tables and did it all again and still the same thing happens with this one table.
The second table that is virtually identical has the same error but does appear in the diagram.
How do I get the first table to show in the diagram and not be read only because I need to delete the associations from time to time.
Thanks
Entity Framework doesn't need association table in the model to work with it.
There should be two navigation properties on either side of the relation - Task has ICollection<Queue> and Queue has ICollection<Task>. To remove association between specific task and queue you either find queue and remove that thask from it's collection, or do the reverse.

Entity Framework Many to Many columns concept

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.

problem in show view when delete foreign key?

I have a student table and an education table, with the PK of the education table as a foreign key of the student table. However, when the education is deleted, the student no longer appears in the view. How do I solve this problem?
From the information you have given, my guess is that you have enforced referencial integrity on your database. This means that when you deleted a row in education, the students that were linked with it were also deleted.
I find that it is good practice to never delete data from tables due to other fields being dependent on them. Instead, you should have a boolean value in the table that is called 'IsDeleted' and just change that to True when you want to 'Delete' it, and when you pull data make sure you filter out anything that has the 'IsDeleted' set to 'True'
Based on what you are asking I think you should first rethink your database structure.
Answer the following questions:
Does it make sense to have a student with a non existant education?
This would be the case if you deleted an education in your Educations table but students with a FK to that education row lived on in your database. This seems to be what you are asking for but it doesn't make much sense as it doesn't mantain data integrity.
Should you be allowed to delete an education if students are enlisted in said education?
If it shouldn`t be allowed then you would only need to disable cascade deleting in your 1 to many relationship and your problem would be solved.
If an eduction is deleted, should all students assigned to said education remain in the data base?
This is what you want but with the structure of your database it is not straightforward to achieve.
Easier solution?
One would be to create 3 tables instead of 2:
Educations
Students
StudentsEducationAssignments
In 1 you store eveything that has to do ONLY with your education entities. In 2 only what has to do with your student entities (note that what type of education they choose is not something that ONLY describes the student). In 3 you store what students are assigned to what educations.
This way, if you delete an education, the students assigned to it will not be deleted, only the information that ties students to that specific education. You keep database integrity easier this way.
Hope this helps.
Maybe an OUTER JOIN instead of an INNER JOIN in your view?
If you show us the view definition we might be able to help more, without it we're just guessing.

MVC Entity Model not showing my table

I have a database with multiple tables, and some basic relationships. Here is an example of the problem I am having:
My Database:
**Org**
ID
Name
etc
**Detail1**
ID
D1name
**Org_Detail1**
Org_ID
Detail1_ID
**Detail2**
ID
D2Name
**Org_Detail2**
Org_ID
Detial1_ID
BooleanField
My problem is, the Org_detail1 table is not showing up in the entity model, but the Org_Details2 table does.
I thought it may have been because the Org_Detail1 table only contains two ID fields that are both primary keys, while the Org_Details2 table contains 2 primary key ID fields as well as a boolean field.
If I add a dummy field to Org_detail1 and update it, it still won't show up and wont allow me to add a new entity relating to the Org_Detail1 table. The table won't even show up in the list, but it is listed under the tables.
Is there any solution to get this table to appear in my model?
Seems like I may just need to completely delete the model and recreate it. Adding dummy fields is the only solution I've found.
Not sure this is an MVC problem.
Does a Detail1 collection turn up in your Org entity and an Org collection show up in your Detail1 entity. This is the normal behaviour for Entity framework for a many to many intersecting table with no other tangible data.
If not then maybe the foreign key constraints are not defined.

Categories