Search code examples
c#oopobject-design

Model a database foreign key in c#


I am creating a calendar application. I have a Appointment table, and a Person table. The 2 are linked by PersonID field in each table.

My question is, should my underlying .Net Appointment object contain a property for the PersonName, and I populate the object from a database view (or stored procedure that joins the tables) or is it more correct to have the Appointment class contain a People class? If the answer is the latter, what is the best way of populating the Appointment/Person object from the database?


Solution

  • Supposing you're not using an ORM, you may take a look at the DAO pattern: http://en.wikipedia.org/wiki/Data_access_object

    I would create two DTOs:

    class Person
    {
        public int id { get; set; }
        public String name { get; set; }
    }
    
    class Appointment
    {
        public int id { get; set; }
        public Date when { get; set; }
        public Person who { get; set; }
    }
    

    And a "full" appointment class:

    class FullAppointment
    {
         private Person person;
         private List<Appointment> appointment;
    }
    

    Then a DTO to get data from the DB:

    class AppointmentDTO
    {
       public FullAppointment retrieveFromDb(int personId)
       {//...}
    }