I am not sure of the correct way to do this.
I want to separate my Entity database model from the model I use throughout my application, as it will have fields in it that I may not want added to the database.
This means, after any Entity call I am doing mapping.
I have come up with this solution rather than use automapper or have mapping calls everywhere in my program (breaking the DRY principal).
My Entity DdSet Model:
public class PeopleTable {
[Key]
public string Id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
}
The Model I would use throughout the application. It has some additional fields and a MapList() mapping function.
public class People : PeopleTable {
public string Job { get; set; }
public string Hobby { get; set; }
public List<People> MapList(List<PeopleTable> input)
{
List<People> list = new List<People>();
foreach (People entry in input)
{
People person = new People();
person.Id = entry.Id;
person.Name = entry.Name;
person.Age = entry.Age;
list.Add(person);
}
return list;
}
}
Getting the data
List<PeopleTable> peopleTableList = await _context.PeopleTable.Select(s => s).ToListAsync();
List<People> peopleList = new People().MapList(peopleTableList);
foreach (person in peopleList){
Console.WriteLine($"{person.Name} is {person.Age} years old");
}
Is this ok? What is best practice? I am thinking there must be something better using the class constructor instead?
Or does everyone just use automapper? I'd rather not have another dependency.