How to create records to record a csv file using FileHelpers

I use Filehelpers to import my database from files. Now I'm working on the reverse process, and I'm having problems with how to create records from my data objects.

All the examples that I can find are derived from the file -> table -> file. I use generic interfaces to convert. I use this code for inbound conversion:

 public interface IConvertCSVRecordToType<T> where T : SimpleBase
  {
    T ConvertCSVRecordToType();
  }

and would like to use something like this for outgoing:

 public interface IConvertTypeToCSVRecord<T> where T : SimpleBase, new()
  {
    void ConvertTypeToCSVRecord(T type);
  }

I use this class to represent CSV records:

  [DelimitedRecord(";"), IgnoreEmptyLines]
  public class CSVRecordFormat : IConvertCSVRecordToType<Material>, 
                                 IConvertTypeToCSVRecord<Material>

I came across TransformToRecordAttribute in the Filehelpers documentation

Class TransformToRecordAttribute

With this attribute, you can mark the method in RecordClass, which is responsibly convert it to specified.

- , , , ?

+3
1

() , :

 public class CSVTableExportProvider<TTable, TRecord>
        where TTable : SimpleBase, new()
        where TRecord : IConvertTypeToCSVRecord<TTable>, new()
 {
    public void ExportTable(string path, string filename, bool continueOnError)
    {
      var rows = _service.GetList<TTable>();
      var records = new List<TRecord>();

      var csvfile = Path.Combine(path, filename);

      var csvFile = new CSVFile<TRecord>(csvfile, continueOnError);

        foreach (var row in rows)
        {
          var rec = new TRecord();
          rec.ConvertTypeToCSVRecord(row);
          records.Add(rec);
        }
        csvFile.ConvertRecordsToFile(records.ToArray());
     }
 }

unit test:

 var provider = new CSVTableExportProvider<Material, MaterialCSVRecordFormat>();
 provider.ExportTable(foldername, filename, true);
0

Source: https://habr.com/ru/post/1727654/


All Articles