views:

117

answers:

2

Please remember that I am not using any ORM tool. I have just written plain ado.net code for classes and methods look like exactly the following. And I am maintaining IDs also.

Suppose I have three tables Teacher, Course and CourseTeacher(join table) for a Many-to-Many relationship and I have designed my classes accordingly.

Now, suppose initially all tables are empty.

And I am executing the following code for the first time.

Course cpp = new Course();
cpp.CourseName = "CPP";

Course java = new Course();
java.CourseName = "Java";

Course cs = new Course();
cs.CourseName = "CS";

Teacher t1 = new Teacher();
t1.TeacherName = "ttt";
t1.AddCourse(cpp);
t1.AddCourse(java);
t1.AddCourse(cs);
t1.SaveOrUpdate();

Teacher t2 = new Teacher();
t2.TeacherName = "ppp";
t2.AddCourse(cpp);
t2.AddCourse(java);
t2.AddCourse(cs);
t2.SaveOrUpdate();

Teacher t3 = new Teacher();
t3.TeacherName = "mmm";
t3.AddCourse(cpp);
t3.AddCourse(java);
t3.AddCourse(cs);
t3.SaveOrUpdate();

How should I handle this situation in my code?

Should I just throw an exception to tell that Course - table don't have any data?

Or, simultaneously populate Course, Teacher and CourseTeacher tables to keep data consistency?

Is the 2nd option is actually possible (Coz, since Course table don't have any data, the program trying to enter data in CourseTable will throw a database exception)?

A: 

Why not make a CourseCatalog Type and append new courses to it first, before assigning teachers to those courses?

John K
The proposed CourseCatalog Type could represent the Course table and it's .SaveOrUpdate() method will cause it to be populated. No more worries about what should be done when teacher has a course because it's already in the Course table.
John K
+2  A: 

This will depend entirely on the business rules for the application.

If the business rules for the application state that new courses are inserted into the database when they are created, then the logical thing to do is likely something like this:

Course java = new Course();
java.CourseName = "Java";
java.SaveOrUpdate();

If, on the other hand, the business rules state that all courses must exist prior to being used, then the proper thing to do is likely to either (A) throw an exception and let the caller handle it, or (B) detect the situation and handle it yourself (possibly by logging and throwing).

Again, it depends on the requirements.

Mike Hofer