Skip to content

Instantly share code, notes, and snippets.

@johnmmoss
Created May 17, 2019 12:59
Show Gist options
  • Save johnmmoss/1a7370268aa37ac46a035d9f618a28cd to your computer and use it in GitHub Desktop.
Save johnmmoss/1a7370268aa37ac46a035d9f618a28cd to your computer and use it in GitHub Desktop.
public void AddOrUpdate<T>(string fileName, params string[] columnNames) where T : class
{
Console.WriteLine($"AddOrUpdate : {fileName} ");
var entityRows = new List<T>();
var csvRows = _csvFileReader.ReadAllRows("DataFiles\\" + fileName);
foreach (var csvRow in csvRows)
{
var instance = (T)Activator.CreateInstance(typeof(T));
for (int index = 0; index < csvRow.Length; index++)
{
var property = instance.GetType().GetProperty(columnNames[index]);
if (property == null)
{
throw new ArgumentNullException($"Property [{columnNames[index]}] not found on type [{instance}]");
}
var propertyValue = Cast(property.PropertyType, csvRow[index]);
property.SetValue(instance, propertyValue);
}
entityRows.Add(instance);
}
_context.Set<T>().AddOrUpdate(entityRows.ToArray());
_context.SaveChanges();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment