S.Vidhya
S.Vidhya

Reputation: 13

I am trying to make a generic method in c# where I want to return a list of records

class Employee
{
  int Id { get; set; }
  string Name { get; set; }
}

class ServiceIEmployeeModel
{
  int Id { get; set; }
  string Name { get; set; }
}

Above Employee and ServiceIEmployeeModel class should auto mapped for its view representation.

//My Generic Method below
public List<U> ListMapping<T, U>(List<T> sourceClass)
{           
            var config = new MapperConfiguration(cfg => { cfg.CreateMap<T, U>(); });
            IMapper mapper = config.CreateMapper();
            List<U> finalData = mapper.Map<List<T>, List<U>>(sourceClass);
            return finalData;
}

List<Employee> employeeData = new List<Employee>();
List<ServiceIEmployeeModel> obj = new List<ServiceIEmployeeModel>();

  ServiceIEmployeeModel obj = new ServiceIEmployeeModel();
  obj.Id = 2;
  obj.Name = "xyz";       

employeeData =
ListMapping<List<ServiceIEmployeeModel>, List<Employee>>(sourceClass:obj);

I am trying to make a generic method in c# where I want to return a list of records.

I have the following code to call the generic method:

But i get an error saying :-
Error CS1503  Argument 1: cannot convert from 'System.Collections.Generic.List<ServiceIEmployeeModel>'
 to 'System.Collections.Generic.List<System.Collections.Generic.List<ServiceIEmployeeModel>>' 
Msc.MasterData.Presentation.Web   C:\Users\sabarimani.a\Desktop\Presentation.Web\Web\Controllers\EmployeeController.cs    59
  Active

Upvotes: 1

Views: 89

Answers (1)

Adil Mammadov
Adil Mammadov

Reputation: 8696

Your ListMapping method accepts type parameters and tries to map list of that types. Pay attention to this line:

List<U> finalData = mapper.Map<List<T>, List<U>>(sourceClass);

When you pass List<ServiceIEmployeeModel> and List<Employee> as type parametets to this method then, T will be List<ServiceIEmployeeModel> and U will be List<Employee> type and your List<U> finalData = mapper.Map<List<T>, List<U>>(sourceClass); line will be actually like:

List<List<Employee>> finalData = mapper
    .Map<List<List<ServiceIEmployeeModel>>, List<List<Employee>>>(sourceClass);

And this is not what you want to achieve. Instead call this method like:

List<ServiceIEmployeeModel> initialData = .....;
employeeData =
    ListMapping<ServiceIEmployeeModel, Employee>(initialData);

Upvotes: 2

Related Questions