'Mapping Foreign Key CSVHelper on ASP.NET Core MVC
I have several foreign key fields, CountyId, SubCountyId, WardId and VarietyId, they link to county, subcounty etc. tables, obviously. Now, I have HeaderValidated as null, MissingFieldFound = null how can I use convert to link the foreign key entries? Right now with the code below, the foreign key entries are not mapped and my related tables end up having new values inserted.
List < Farmer > farmers = new List < Farmer > ();
#
region Read CSV
var path = $ "{Directory.GetCurrentDirectory()}{@"\
wwwroot\ files "}" + "\\" + fileName;
var conf = new CsvConfiguration(CultureInfo.InvariantCulture) {
HeaderValidated = null,
MissingFieldFound = null,
};
using(var reader = new StreamReader(path))
using(var csv = new CsvReader(reader, conf)) {
csv.Read();
csv.ReadHeader();
while (csv.Read()) {
var farmer = csv.GetRecord < Farmer > ();
farmers.Add(farmer);
}
}
return farmers;
The Farmer class looks like this.
public class Farmer
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public int? VarietyId { get; set; }
public virtual Variety Variety { get; set; }
public int? CountyId { get; set; }
public virtual County County { get; set; }
public int? SubCountyId { get; set; }
public virtual SubCounty SubCounty { get; set; }
public int? WardId { get; set; }
public virtual Ward Ward { get; set; }
public int? TownId { get; set; }
public virtual Town Town { get; set; }
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
