Replies: 4 comments 6 replies
-
So in the first example you want a missing field to be an empty string, and in the second example you want it to be null? If that's the case, just using |
Beta Was this translation helpful? Give feedback.
-
Thanks for you help but optional don't work for me. I have two case. In my second example, the column "Entity" missing. If I use only optional(). Can you confirm me what you told me previously ? Maybe the problem is with my class. Becarefull my version of csvhelper is 19.0.0 |
Beta Was this translation helpful? Give feedback.
-
void Main()
{
var s = new StringBuilder();
s.Append("Id,Name\r\n");
s.Append("1,\r\n");
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
};
using (var reader = new StringReader(s.ToString()))
using (var csv = new CsvReader(reader, config))
{
csv.Configuration.RegisterClassMap<FooMap>();
csv.GetRecords<Foo>().ToList().Dump();
}
}
private class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
private class FooMap : ClassMap<Foo>
{
public FooMap()
{
Map(m => m.Id);
Map(m => m.Name).Optional();
}
} void Main()
{
var s = new StringBuilder();
s.Append("Id\r\n");
s.Append("1\r\n");
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
};
using (var reader = new StringReader(s.ToString()))
using (var csv = new CsvReader(reader, config))
{
csv.Configuration.RegisterClassMap<FooMap>();
csv.GetRecords<Foo>().ToList().Dump();
}
}
private class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
private class FooMap : ClassMap<Foo>
{
public FooMap()
{
Map(m => m.Id);
Map(m => m.Name).Optional();
}
} |
Beta Was this translation helpful? Give feedback.
-
Actually if you have header with 2 items and records with one
you will get exception
The same happen when you have csv without header, that was the reason I found this thread |
Beta Was this translation helpful? Give feedback.
-
Hi everyone,
Version CsvHelper ==> 19.0.0.
I would like the value of my optional column to be null if the column is not present and equal to its value if the column is present.
Example with column Engine:
CDE;Engine
201901182;F2BFA602DM ==> value Engine = "F2BFA602DM"
201900579; ==> value Engine = ""
201900641;F2BFA602DM ==> value Engine = "F2BFA602DM"
Example without column Engine:
CDE
201901182 ==> value Engine = null
201900579 ==> value Engine = null
If the value is null then I do not update my data in BDD on the other hand if the value is empty then I update my data.
I tried a lot of things but finally I can do the opposite with the following code.
Map(m => m.EngineName).Name(Translations.Resources.Translation.Import_Engine_Name).Optional().TypeConverterOption.NullValues(String.Empty);
Thank you for your help.
Beta Was this translation helpful? Give feedback.
All reactions