I have two related models
ModelBase.cs
public class ModelBase
{
public virtual ModelBase Map(DataRow dr)
{
return this;
}
}
User.cs which derives from above class. In the future I want to have more classes like user where I can map fields from DataRow to my properties
public class User : ModelBase
{
public string Id { get; set; }
public string Surname { get; set; }
public string Name { get; set; }
public User() { }
public override User Map(DataRow dr)
{
var config = new MapperConfiguration
(cfg => cfg.CreateMap<DataRow, User>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(row => row["x"]))
.ForMember(dest => dest.Name, opt => opt.MapFrom(row => row["xx"]))
.ForMember(dest => dest.Surname, opt => opt.MapFrom(row => row["xxx"]))
);
var mapper = config.CreateMapper();
return mapper.Map<User>(dr);
}
}
I am receiving Users as DataTable so I have created simple method to convert it to list, but if there will be more classes (all received as DataTables), I want my function to be flexible and valid with rest of my models. The question is how can I use this dynamically?
Utility.cs
public class DataTableConverter<T> where T : ModelBase
{
public static List<T> ConvertToList(DataTable dt, Type type)
{
var results = new List<T>(dt.Rows.Count);
foreach (DataRow row in dt.Rows)
{
// Here I want to call Map function from dynamic model and add it to results
}
return results;
}
}