views:

268

answers:

1

Can someone help me understand how best to model a composition relationship?

If for instance I have a student whom can have many schedules, I would create roughly:

class Student
{
  prop long Pk { get; set; }
  prop string Name { get; set; }
  prop List<Schedule> Schedules { get; set; }
}

class Schedule
{
  prop string Semester { get; set; }
  prop List<Course> Courses{ get; set; }
}

Somewhere down the line I may have a Schedule object, and will wish to identify which student it belongs to. I want to be able to write Schedule.Student.Name, and receive the student's name in return. Do I add a Student property to my Schedule object as well?

My application has been passing a Student Pk to my Schedule object in order to do CRUD functionality. I'm keeping the Student PK as a private variable in order to keep a handle on it if I need it.

As my application becomes more complex, I'm finding it hard to maintain what I've been doing. What are your suggestions for me? What else can I consult (books/links) to get a refresher and better handle on these fundamentals?

+2  A: 

"I want to be able to write Schedule.Student.Name, and receive the student's name in return. Do I add a Student property to my Schedule object as well?" Yes.

What you are describing (supporting both foreign keys for lookup and object references for easy navigation of the object graph) sounds like a really good match for an object-relational mapper (ORM). A good ORM will automatically load the associated object/objects for you using the FK/PK (e.g. if the Schedule has a StudentPK field then the mapper will handle loading/mapping of the Student property for you). There are many products of this type: you can use built-in .NET frameworks such as the Entity Framework, open-source ones such as NHibernate or commercial products such as LightSpeed, LLBLGen, EntitySpaces or OpenAccess (disclosure: I work for a company that makes a commercial ORM). Google for ORM or object-relational mapper, or check Wikipedia, for an overview of the kind of thing I'm describing.

itowlson
But if I add a Student property to my Schedule property, whats stopping me from doing this:Student.Schedules[0].Student.Schedules[1].Student.Schedules[0].Student.Schedules[0].Name.Isn't this a circular reference? Is this allowed?
Yes, this is allowed. It doesn't cause an infinite regress because (a) if you are creating the objects by hand, you'll reuse objects that already exist (e.g. when you create a Schedule, you'll set its Student property to the existing Student, not create a new Student) or (b) if you are using an ORM it will spot that a key refers to an existing object and reuse it. Also most ORMs will lazy load by default: e.g. when constructing a Student, they'd populate the Schedules collection when you ask for it (and conversely only populate Schedule.Student when you ask for it).
itowlson