ChoETL
ChoETL copied to clipboard
Consider adding ChoCSVRecordFieldConfiguration<T>
Please consider adding a generic version of ChoCSVRecordFieldConfiguration since a generic version of WithField already exist on the reader.
So after a good night sleep I figure a better way to solve it for myself that support strongly typed mapping. Feel free to incorporate this code however you see fit.
public class CSVTransformer<T> : ChoCSVRecordConfiguration
{
public CSVTransformer<T> Map<TProperty>(Expression<Func<T, TProperty>> property, string fieldName)
{
CSVRecordFieldConfigurations.Add(new ChoCSVRecordFieldConfiguration(property.GetMemberName(), 0)
{
FieldName = fieldName,
});
return this;
}
public Action<T> AfterRecordLoad { get; set; }
}
I intentionally name this different than ChoCSVRecordConfiguration in case you wish to make ChoCSVRecordConfiguration<T>
this will not break my code.
Here are the example usage
public class ChoGenericMapperTest
{
public class Emp
{
public string Name { get; set; }
public string Other { get; set; }
public string MyId { get; set; }
}
[Test]
public void TestMapping()
{
string csv = @"Id, Name, City
1, Tom, NY
2, Mark, NJ
3, Lou, FL
4, Smith, PA
5, Raj, DC
";
ChoCSVRecordConfiguration config = new ChoCSVRecordConfiguration();
config.CSVRecordFieldConfigurations.Add(new ChoCSVRecordFieldConfiguration("MyId", 0)
{
FieldName = "Id",
});
config.CSVRecordFieldConfigurations.Add(new ChoCSVRecordFieldConfiguration("Name", 0)
{
FieldName = "Name",
});
config.CSVRecordFieldConfigurations.Add(new ChoCSVRecordFieldConfiguration("Other", 0)
{
FieldName = "City",
});
config.WithFirstLineHeader(false);
using (var reader = ChoCSVReader<Emp>.LoadText(csv, Encoding.ASCII, config))
{
reader.AfterRecordLoad += (sender, args) => { };
Console.WriteLine(reader.ToList().DumpAsJson());
}
}
[Test]
public void TestNewMappingMethod()
{
string csv = @"Id, Name, City
1, Tom, NY
2, Mark, NJ
3, Lou, FL
4, Smith, PA
5, Raj, DC
";
var config = new CSVTransformer<Emp>();
config.Map(emp => emp.Name, "Name");
config.Map(emp => emp.Other, "City");
config.Map(emp => emp.MyId, "Id");
config.WithFirstLineHeader(false);
using (var reader = ChoCSVReader<Emp>.LoadText(csv, Encoding.ASCII, config))
{
reader.AfterRecordLoad += (sender, args) => { };
Console.WriteLine(reader.ToList().DumpAsJson());
}
}
}
Added support of this feature in 1.0.2.1-alpha1 package
Pls try and let me know
Thank you. Will give it a try and let you know.