Return class as JSON with one extra field in API using Entity Framework

Viewed 318

I have a class Employee with many properties in it and when I want to read it from the database and return a list of it. I want to add an extra field to it.

Currently it's like this:

return await _context.Employees.ToListAsync();

I don't want to use Select command after Employee because as far as I know I have to list all my properties in the Employee class to be able to add an extra one like below:

return await _context.Employees.Select(em => new 
{
   em.Firstname, // In employee class
   em.Lastname, // In employee class
   ... // Other properties in employee class
   EXTRAFIELD = "Data" // Extra field with any data I want to add to employee
}).ToListAsync();

But in the solution above I have to list all my fields in employee class.

I don't want to do as below as it puts employee in a new object names em:

return await _context.Employees.Select(em => new 
    {
       em,
       EXTRAFIELD = "Data" // Extra field with any data I want to add to employee
    }).ToListAsync();

Is there a way to tell DbContext (_context) to return Employee fields and add "this new field" in it (create new object which has same properties as Employee with one extra)?

1 Answers

How about to create and return a custom object that will inherit Employee properties? And you can add extra generic field, for example:

public class CustomEmployee<T> : Employee
{
    public T Data { get; set; }
}

I know you don't want to copy values from object to object with Select, but we can create something like this:

public class CustomEmployee<T> : Employee
{

    public CustomEmployee() { } //for cases if you don't want to copy values while creating an instance

    public CustomEmployee(Employee employee)
    {
        foreach (PropertyInfo prop in employee.GetType().GetProperties())
        {
            PropertyInfo prop2 = employee.GetType().GetProperty(prop.Name);
            prop2.SetValue(this, prop.GetValue(employee, null), null);
        }
    }

    public T Data { get; set; }
}

In constructor you have to pass an inherited instance Employee, and code above will copy values from Employee to CustomEmployee.

And use like this:

return await _context.Employees.Select(em => new CustomEmployee(em)<string> 
{ 
    Data = "Extra data" 
}).ToListAsync();
Related