Book a Demo

Author Topic: How to show one-to-many in code?  (Read 2078 times)

peter king

  • EA User
  • **
  • Posts: 20
  • Karma: +0/-0
    • View Profile
How to show one-to-many in code?
« on: November 21, 2009, 06:27:19 pm »
Hi friend,

If i show the relationshion btween Company and Employee
1. Compnay has 1..M Employees
2. An EMployee can be of 1 Company

If i show this in code C#:

Code: [Select]
public class Company
{
      List<Empoyee> myEmployees; // [1..m] relationship
      Employee emp;

        public Company()
        {
              myEmployees = new List<Employee>();
        }

        public void addEmployee(string fname, string lname)
        {
               //reference to the class Employee
               emp = new Employee();
               emp.InitEmployee(fname, lname);
               myEmployees.add(emp);

               //saving the collection
               emp.SaveEmployee(myEmployee);
        }
}

Code: [Select]
public class Employee
{
      //delcaration or members FName and LName
       public void InitEmployee(string fname, string lname)
       {
                  FName = fname;
                  LName = lname;
       }

       public void SaveEmployee(List<Employee> empCollection)
       {
              foreach(Employee obj in empCollection)                      
              {
                 //Save each object to SQL DB
              }
       }      
}

is this the way to show 1..M relationship between classes?

Thanks
« Last Edit: November 22, 2009, 12:23:44 am by umlontherun111 »

Geert Bellekens

  • EA Guru
  • *****
  • Posts: 13523
  • Karma: +574/-33
  • Make EA work for YOU!
    • View Profile
    • Enterprise Architect Consultant and Value Added Reseller
Re: How to show one-to-many in code?
« Reply #1 on: November 23, 2009, 08:07:08 pm »
Could be, it all depends on the navigability of the relation.

Your solution implies a relation that is navigable from the company --> employee.

If the navigability would be the other way around: employee --> company then the employee would likely have an attribute of type Company.

If the relation would be navigable in both way's then both the Company as the Employee would have a reference to the other.

Geert