SQL table to classes

661 Views Asked by At

I have a modelling question that I need help understanding.

I have a table called Employee and a table called Office. There is a 1 to many relationship between the classes (1 employee has one office and one office has multiple employees).

The goal is to create classes from those tables and I have found two ways:

1:

public class Employee
{
    private string Name   { get; set; }
    private Office Office { get; set; }
}

public class Office
{
    private string OfficeName { get; set; }
}

2:

public class Employee
{
    private string Name {get; set;}
}

public class Office
{
    private string OfficeName       { get; set; }
    private List<Employee>Employees { get; set; }
}

Which way is the correct way to model this ?

1

There are 1 best solutions below

4
StaticBeagle On BEST ANSWER

I find the second approach to be easier to work with (more natural). Reason being, when you model your data this way:

public Class Employee
{
    string Name {get; set;}
}

public Class Office
{
    string OfficeName {get; set}
    List<Employee>Employees {get; set}
}

You can create these tables (or use entity framework to create the tables for you) in the following manner:

// Office table             // Employee table
-----------------           ----------------------------------
| Id(PK) | Name | --------> | Id(PK) | OfficeId(FK) | Name |  
-----------------           ----------------------------------

// PK: Primary Key
// FK: Foreign Key

The one-to-many relationship is represented via the FK in the employee table and the employee has a FK to the office where he/she belongs. Then by using simple joins you can get all info you need from the tables. e.g.

Get all employees for an office

    SQL: SELECT Offices.OfficeId, Offices.Name, Employees.Name 
         FROM Offices
         JOIN Employees ON Offices.Id = Employees.OfficeId
         WHERE Offices.Name = 'some_name'
    // Or you can use LINQ had you had used Entity Framework

This would've been a bit more complicated if you had used your first approach.