简体   繁体   中英

Csv Helper Fluent Class Mapping adds a leading zero to int field when mapped to string property

I have a string property called TimeClockCode. Which is mapped to index(0) of the csv file. Index(0) contains integers such as 11565. But after mapping to string TimeClockCode,

Like this: Map(p => p.TimeclockCode).Index(0);

or like this: Map(p => p.TimeclockCode).ConvertUsing(row => row.GetField<string>(0));

both result in string 011565.

I solved this by reading it as an int and calling toString on it.

Map(p => p.TimeclockCode).ConvertUsing(row => row.GetField<int>(0).ToString()); Which gave me desired results of 11565.

Am I missing something about the implementation of fluent mappings? Where is the leading zero coming from?

I couldn't replicate your problem. I used this code:

static void Main(string[] args)
{
    var s = "\"11565\",\"a\",\"012\",\"4.5\",\"01\",\"555\"\r\n";
    using (var sr = new StringReader(s))
    {
        var csv = new CsvReader(sr);
        csv.Configuration.HasHeaderRecord = false;
        csv.Configuration.RegisterClassMap<MyClassMap>();
        while (csv.Read())
        {
            var record = csv.GetRecord<MyClass>();

        }
    }
}

public class MyClass
{
    public string Test { get; set; }
    public string TimeclockCode { get; set; }
}

public sealed class MyClassMap : CsvClassMap<MyClass>
{
    public MyClassMap()
    {
        Map(p => p.TimeclockCode).Index(0);
        Map(p => p.Test).Index(2);
    }
}

I can only assume that the value in the CSV is 011565 or that you have some other issue that is not evident from the text of the question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM