forked from JoshClose/CsvHelper
-
Notifications
You must be signed in to change notification settings - Fork 1
Fluent Class Mapping
akiller edited this page Feb 15, 2012
·
7 revisions
You can map custom class properties to CSV fields using a separate class mapping file. This is useful if you don't have control over the classes you need to read and write with.
CSV File
String Field,Guid Field,Int Field
row 1,11111111-1111-1111-1111-111111111111,1
row 2,22222222-2222-2222-2222-222222222222,2
row 3,33333333-3333-3333-3333-333333333333,3
Custom Class
public class CustomClass
{
public string StringProperty { get; set; }
public Guid GuidProperty { get; set; }
public int IntProperty { get; set; }
}
Mapping By Field Names
You can map class properties to CSV fields using the header names.
public sealed class CustomClassMap : CsvClassMap<CustomClass>
{
public CustomClassMap()
{
Map( m => m.StringProperty ).Name( "String Field" );
Map( m => m.GuidProperty ).Name( "Guid Field" );
Map( m => m.IntProperty ).Name( "Int Field" );
}
}
Mapping By Indexes
You can map class properties to CSV fields using the index of the field.
public sealed class CustomClassMap : CsvClassMap<CustomClass>
{
public CustomClassMap()
{
Map( m => m.StringProperty ).Index( 0 );
Map( m => m.IntProperty ).Index( 2 );
Map( m => m.GuidProperty ).Index( 1 );
}
}
Ignoring Properties
If you want a property to be skipped when reading or writing, ignore the field.
public sealed class CustomClassMap : CsvClassMap<CustomClass>
{
public CustomClassMap()
{
Map( m => m.StringProperty ).Index( 0 );
Map( m => m.GuidProperty ).Ignore();
Map( m => m.IntProperty ).Ignore();
}
}
Using Custom Type Converters
If you have a type that can't be automatically converted, you can use a custom type converter.
public sealed class CustomClassMap : CsvClassMap<CustomClass>
{
public CustomClassMap()
{
Map( m => m.StringProperty ).Index( 0 );
Map( m => m.GuidProperty ).Index( 1 );
Map( m => m.IntProperty ).Index( 2 ).TypeConverter<MyCustomTypeConverter>();
}
}
Mapping Example
The following example demonstrates how to use a class mapping by adding it to the Configuration.ClassMapping property.
CsvHelper csv = new CsvHelper(File.OpenRead("data.csv"));
csv.Configuration.ClassMapping<CustomClassMap, CustomClass>();
IEnumerable<CustomClass> data = csv.Reader.GetRecords<CustomClass>();