Click here to Skip to main content
15,881,044 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
Hi Everyone.
I am new to OOP and trying to make class association in C#. I have two classes called Department and Employee.
I want to get all the employees in one Department and the other way around. I have searched on Google but was unlucky.I am not sure that the way I am doing is right or wrong.

Any help would be appreciated. Please see the code. Thanks in advance

---------------------------Department--------------------------
C#
public class Department
    {
        private int _DepartID;
        private string _DepartName;
        private string _DepartDescp;
       
       public int DepartmentID
        {
            get { return _DepartID; }
            set { _DepartID = value; }
        }             

        public string DepartmentName
        {
            get { return _DepartName; }
            set { _DepartName = value; }
        }      

        public string DepartDescription
        {
            get { return _DepartDescp; }
            set { _DepartDescp = value; }
        }
     
        public override string ToString()
        {
            return this.DepartmentID + " " + this._DepartName  +" " +   this.DepartDescription; 
        }

        List<employee> EmployeeList=new List<employee>();

        public  List<employee> Empoyees(Employee objEmp)
        {
            EmployeeList.Add(objEmp);
            return EmployeeList;
        }                   
                  
    }
------------------------------------Employee------------------------
C#
public class Employee
   {
       private int _employeeID;
       private string _empFirstName;
       private string _empLastName;
       private string _empTitle;


       public int EmployeeID
       {
           get { return _employeeID; }
           set { _employeeID = value; }
       }

       public string EmpFirstName
       {
           get { return _empFirstName; }
           set { _empFirstName = value; }
       }

       public string EmpLastName
       {
           get { return _empLastName; }
           set { _empLastName = value; }
       }

       public string EmpTitle
       {
           get { return _empTitle; }
           set { _empTitle = value; }
       }

       public override string ToString()
       {
           return this.EmpTitle + " " + this.EmpFirstName + " " + this._empLastName + " " + this._employeeID.ToString ();
       }

   }
-------------------Code behind button-------------------

C#
Department obj_Depart = new Department();
Employee obj_Emp = new Employee();

obj_Emp.EmployeeID =1011;
obj_Emp.EmpTitle = "Mr";
obj_Emp.EmpFirstName = "Test1";
obj_Emp.EmpLastName = "Test2";

obj_Depart.DepartmentID = 1201;
obj_Depart.DepartmentName = "IT Department";
obj_Depart.DepartDescription = "Business center";

obj_Depart.Empoyees(obj_Emp);


listBox1.Items.Add(obj_Depart);
Posted
Updated 20-Aug-12 5:35am
v2
Comments
[no name] 20-Aug-12 11:39am    
"I want to get all the employees in one Department and the other way around"... makes no sense. I doubt that your code even compiles since your Department Employees is a List and you are trying to stick an Employee object into it, obj_Depart.Empoyees(obj_Emp).

You have two ways to associate Employees and Departments using objects. One is to have a Department property in the Employee object and the other is to have a collection of Employee objects in the Department object. You will also, at the minimum have either a collection of all Department or all Employee objects.

The way you have it, if you have a collection of all Deparment objects, which contain a collection Employee objects, you can get all Employee objects using LINQ.

var allEmployees = Departments.SelectMany(d => d.EmployeeList);


if you want to get the deparment of an employee

var employeeDepartment = Departments.FirstOrDefault(d => d.Employees.FirstOrDefault(e => e == employee) != null));


However, I think you will find it easier to have a Deparment property in the Employee class than to have a collection in the Department class.

Note: Using id's for associations is more of a relational data concept, and you are in the object world with C#.

Your question is a bit unclear, so I am only guessing at what you want.
 
Share this answer
 
Comments
Member 1565922 20-Aug-12 20:18pm    
Thanks.
Member 1565922 20-Aug-12 20:24pm    
Actually, as I am quite new to the OOP concepts I was trying to make an association between classes.I used class diagram in VS and then I created two classes and then using Tools panel I created an association between the classes(Employee and Department). I was trying to make that work but I became stuck in it.can you also please suggest books or other articles.Thanks in advance.
Clifford Nelson 20-Aug-12 20:35pm    
If you were interested in associating the two, the best would be to have the empolyee record have a department property, and the department have an employee collection. Then it is really easy. What you end up with is a parent child relationship where the child points back to the parent. This is quite common, and if you investigate a lot of the objects that are written by Microsoft you will see a parent field that points back up the chain. I have found that the Heads First series has a lot to offer to try to explain things, so would recommend http://www.amazon.com/Head-First-Object-Oriented-Analysis-Design/dp/0596008678/ref=sr_1_1?ie=UTF8&qid=1345509191&sr=8-1&keywords=heads+first+object+oriented+programming.
Member 1565922 20-Aug-12 22:23pm    
It's a great book, just looked at Google books, I will get that asap. Thanks a lot.
Well, the one way i would approach is add "DepartmentID" property in the Employee class (like a foreign key). Add Employee to a List<employee> initially with "DepartmentID" null or 0 and then using your GUI, assign a Department to the employees i.e. populate the "DepartmentID" property and that's it. You don't need to have List<> in the data classes, they should only contain data for the individual entity. Operations should be separated out to business classes.

One Department can have many EMployees but one Employee can be in only one Department, its one to many relation and not a many to many (AFAIT).

Hope this helps.

[EDIT:]I really don't see a reason why my idea would be downvoted unless you or whoever downvoted it had a better solution or idea. Anyway, here is a little something to get you started. The following code shows 2 ways of doing of doing it (atleast in my world so far) - layered and unlayered:

C#
public class Department
    {
        public int DepartmentID { get; set; }

        public string DepartmentName { get; set; }

        public string DepartDescription { get; set; }
    }



C#
public class Employee
    {
        public int EmployeeID { get; set; }

        public string EmpFirstName { get; set; }

        public string EmpLastName { get; set; }

        public string EmpTitle { get; set; }

        public int DepartmentId { get; set; }
    }


C#
static void Main(string[] args)
        {
            //unlayered style
            List<Department> departments = new List<Department>();
            List<Employee> employees = new List<Employee>();

            Department d = new Department();
            d.DepartmentID = 1;
            d.DepartmentName = "xyz";
            d.DepartDescription = "abc";
            departments.Add(d);
            Department d1 = new Department();
            d1.DepartmentID = 2;
            d1.DepartmentName = "xyz2";
            d1.DepartDescription = "abc2";
            departments.Add(d1);

            Employee e;
            for (int i = 0; i < departments.Count; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    e = new Employee();
                    e.DepartmentId = departments[i].DepartmentID;
                    e.EmpFirstName = "add";
                    e.EmpLastName = "test";
                    e.EmployeeID = 123;
                    e.EmpTitle = "adf";
                    employees.Add(e);
                }
            }
            //querying for an employee name in a particular department
            string employeename = employees.Where(x => x.DepartmentId == departments.Where(y => y.DepartmentName == "xyz").Select(y => y).FirstOrDefault().DepartmentID).Select(x => x.EmpFirstName).FirstOrDefault();
            Console.WriteLine(employeename);
            
            //layered style - using Business Logic class to define an employee list prop which you can add to
            DepartmentBL dbl = new DepartmentBL();
            for (int i = 0; i < departments.Count; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    e = new Employee();
                    e.DepartmentId = departments[i].DepartmentID;
                    e.EmpFirstName = "add";
                    e.EmpLastName = "test";
                    e.EmployeeID = j+1;
                    e.EmpTitle ="adf" + (j+1).ToString();
                    dbl.EmployeeList.Add(e);
                }
            }

            Console.WriteLine("Employees added :" + dbl.EmployeeList.Count.ToString());


        }


Department and Employee data classes don't define any operation, that should be the task of a separate class (lookup n-tier architecture), in this case DepartmentBL (BL = Business Layer or Logic). It exposes an Employees list property that you can add Employees to, since a department "consists of" employees. Hope this helps to some extent.
 
Share this answer
 
v2
Comments
Member 1565922 20-Aug-12 12:18pm    
Sorry, can you please give an example.Thanks
Member 1565922 20-Aug-12 14:35pm    
Great thanks a lot. very helpful

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900