Link to home
Start Free TrialLog in
Avatar of satmisha
satmishaFlag for India

asked on

Populate Department class which contains a list of 'Employees' where there is no key from another entity class

How to loop through an entity 'DepartmentEmployee' and fill Department class which contains a list of 'Employees' where there is no key present.

I want to fill my Department class from the entity DepartmentEmployee mentioned below, please suggest.


public class Department
{
	public int DeptID { get; set; }
	public List<Employees> DetailData { get; set; }
}
   
public class Employees
{
	public string EmpName { get; set; }
	public DateTime? DOJ { get; set; }
}

public class DepartmentEmployee
{
	public string DeptID { get; set; }
	public string EmpName { get; set; }
	public DateTime? DOJ { get; set; }
}
	
Data present in the DepartmentEmployee is:
	
  DeptID     EmpName		DOJ
	1		A		22-12-2020
	1		B		22-12-2020
	2		C		23-12-2020
	2		D		23-12-2020

Open in new window

Avatar of it_saige
it_saige
Flag of United States of America image

You mean something like this:

using System;
using System.Collections.Generic;
using System.Linq;


namespace EE_Q29187042
{
    class Program
    {
        static void Main(string[] args)
        {
            var data = new[]
            {
                new DepartmentEmployee {DeptID = "1", EmpName = "A", DOJ = new DateTime(2020, 12, 20)},
                new DepartmentEmployee {DeptID = "1", EmpName = "B", DOJ = new DateTime(2020, 12, 20)},
                new DepartmentEmployee {DeptID = "2", EmpName = "C", DOJ = new DateTime(2020, 12, 20)},
                new DepartmentEmployee {DeptID = "2", EmpName = "D", DOJ = new DateTime(2020, 12, 20)}
            };


            var id = default(int);
            var departements = (from de in data
                                where int.TryParse(de.DeptID, out id)
                                group de by id into depts
                                select new Department { DeptID = depts.Key, DetailData = depts.Select(x => new Employee { EmpName = x.EmpName, DOJ = x.DOJ }).ToList() });


            foreach (var department in departements)
            {
                Console.WriteLine($"Department ID: {department.DeptID}");
                foreach (var employee in department.DetailData)
                {
                    Console.WriteLine($"{{ Employee Name: {employee.EmpName}, DOJ: {employee.DOJ.Value:dd-MM-yyyy} }}");
                }
                Console.WriteLine();
            }


            Console.ReadLine();
        }
    }


    class Department
    {
        public int DeptID { get; set; }
        public List<Employee> DetailData { get; set; }
    }


    class Employee
    {
        public string EmpName { get; set; }
        public DateTime? DOJ { get; set; }
    }


    class DepartmentEmployee
    {
        public string DeptID { get; set; }
        public string EmpName { get; set; }
        public DateTime? DOJ { get; set; }
    }
}

Open in new window

Which produces the following output -
User generated image-saige-
Avatar of satmisha

ASKER

Thank you so much, it_saige .

But I am getting one error on line

where int.TryParse(de.DeptID, out id) 

Open in new window

it says that 'Argument 1: cannot convert from 'int' to 'string'.
Hi It_saige, I got another error message with the above-said code while using the for each loop, it says:

This function can only be invoked from LINQ to Entities.

Open in new window


Appreciate your help....
The first issue is because the class that you originally defined is using an int instead.  Simple change:

using System;
using System.Collections.Generic;
using System.Linq;


namespace EE_Q29187042
{
    class Program
    {
        static void Main(string[] args)
        {
            var data = new[]
            {
                new DepartmentEmployee {DeptID = 1, EmpName = "A", DOJ = new DateTime(2020, 12, 20)},
                new DepartmentEmployee {DeptID = 1, EmpName = "B", DOJ = new DateTime(2020, 12, 20)},
                new DepartmentEmployee {DeptID = 2, EmpName = "C", DOJ = new DateTime(2020, 12, 20)},
                new DepartmentEmployee {DeptID = 2, EmpName = "D", DOJ = new DateTime(2020, 12, 20)}
            };


            var departements = (from de in data
                                group de by de.DeptID into depts
                                select new Department { DeptID = depts.Key, DetailData = depts.Select(x => new Employee { EmpName = x.EmpName, DOJ = x.DOJ }).ToList() });


            foreach (var department in departements)
            {
                Console.WriteLine($"Department ID: {department.DeptID}");
                foreach (var employee in department.DetailData)
                {
                    Console.WriteLine($"{{ Employee Name: {employee.EmpName}, DOJ: {employee.DOJ.Value:dd-MM-yyyy} }}");
                }
                Console.WriteLine();
            }


            Console.ReadLine();
        }
    }


    class Department
    {
        public int DeptID { get; set; }
        public List<Employee> DetailData { get; set; }
    }


    class Employee
    {
        public string EmpName { get; set; }
        public DateTime? DOJ { get; set; }
    }


    class DepartmentEmployee
    {
        public int DeptID { get; set; }
        public string EmpName { get; set; }
        public DateTime? DOJ { get; set; }
    }
}

Open in new window


As for your second error.  Are you dealing with Entities here or classes like the ones you have defined?

-saige-
I am having classes as I defined here but with many columns that includes varoud datatypes like (int, varchchar, bit etc..)
Try creating a new console project and use just the code I posted.  Tell me if you get the same error.

-saige-
H it_seige,

I tried your code in the console it worked absolutely fine. whereas in  my case in the below line

var result = getDataFromStoreProcedure();//get data from sp

var Id = default(int);
var Department = (from de in result
              where int.TryParse(de.VehicleId, out Id)//Here I gets error message
              group de by Id into dept
              select new Department { VehicleId = dept.Key, DetailData = dept.Select(x => new Employee { NumTrips = x.NumTrips, HomeCount = x.HomeCount }).ToList() }); 

Open in new window


After further amazing your code I found that you have used array whereas in my case I am filling my result variable via store procedure and then try to loop over to fill my entity classes, Dept & employee.

I get an error stating 'Argument 1: cannot convert from int to string'.

Appreciate your help.
Try this instead:

var result = getDataFromStoreProcedure();//get data from sp


var Department = (from de in result
                  group de by de.VehicleId into dept
                  select new Department { VehicleId = dept.Key, DetailData = dept.Select(x => new Employee { NumTrips = x.NumTrips, HomeCount = x.HomeCount }).ToList() });

Open in new window


-saige-
Thank you, it_saige.

Appreciate your inputs...
Thanks, it_seige,  you nailed i :-)

Your following suggested solution worked for me, just having the last issue within that, here in this we have only one column from the department class i.e. DeptID, what if I have more columns than how could I accommodate them too here?

var departements = (from de in data
                                group de by de.DeptID into depts
                                select new Department { DeptID = depts.Key, DetailData = depts.Select(x => new Employee { EmpName = x.EmpName, DOJ = x.DOJ }).ToList() });




class Department
    {
        public int DeptID { get; set; }
       public string Description { get; set; }
       public DateTime DeptDate { get; set; }
        public Bit IsExist{ get; set; }
        public List<Employee> DetailData { get; set; }    }

Open in new window


This is what I am trying but not working for me :-(

var departements = (from de in data group de by de.DeptID into depts                           select new Department { DeptID = depts.Key, 
                                 /*This is not working for me*/
                                 DeptID = depts.Key, 
                                 Description = depts.Description,
                                 DeptDate = depts.DeptDate,
                                 IsExist = depts.IsExist
         DetailData = depts.Select(x => new Employee { EmpName = x.EmpName, DOJ = x.DOJ }).ToList() });

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of it_saige
it_saige
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank You, Saige. It is working perfectly fine. Just want to know, can I loop through Department class as it is already filled by your code instead looping through var departments...?

 foreach (var department in departements)            
{
   Console.WriteLine($"{{ Department ID: {department.DeptID}, 
                           Description: {department.Description}, 
                           Date: {department.DeptDate}, 
                           IsExist: {department.IsExist} }}");                 
      foreach (var employee in department.DetailData)                 {                           Console.WriteLine($"{{ Employee Name: {employee.EmpName}, DOJ:          {employee.DOJ.Value:dd-MM-yyyy} }}");                 }                          Console.WriteLine(); 
}

Open in new window

You must understand that DepartmentEmployees is a combination of Departments and Employees.  As such, simply looping through Departments will not suffice.  According to the requirements supplied, a List of Employees depends upon, at least, their department id.  So grouping by the data supplied by DepartmentEmployees provides the combination of both Departments and Employees per Department.

-saige-
Hi it_saige,

I just noticed that code is not returning all the data, if you see in the screenshot it is returning 03 rows whereas List contains 04 rows, i used above mentioned code...

var data = new[] { new DepartmentEmployee {DeptID = 1, Description = "Department 1", DeptDate = new DateTime(2000, 1, 1), IsExist = true, EmpName = "A", DOJ = new DateTime(2020, 12, 20)},
new DepartmentEmployee {DeptID = 1, Description = "Department 1", DeptDate = new DateTime(2000, 1, 1), IsExist = true, EmpName = "B", DOJ = new DateTime(2020, 12, 20)},  
new DepartmentEmployee {DeptID = 2, Description = "Department 2 (Old)", DeptDate = new DateTime(2000, 1, 1), IsExist = false, EmpName = "C", DOJ = new DateTime(2020, 12, 20)},  
new DepartmentEmployee {DeptID = 2, Description = "Department 2 (New)", DeptDate = new DateTime(2000, 2, 1), IsExist = true, EmpName = "D", DOJ = new DateTime(2020, 12, 20)} };
Which now produces the following output -
User generated image
 
Please ignore above one, I mistakenly read something wrong... .code is fine... thank you