如何使用FileHelpers分隔具有不同RowType的行?

时间:2018-08-02 22:56:06

标签: c# etl filehelpers rhino-etl

例如,我有一个带有两行的下一个文件test.txt:

Type00007P 008 PPL

Type00230J 190 1

代码中的下一个使用Rhino-ETL Nuget的类将这些行插入我的数据库中:

public class Type00007P
{
    [FieldFixedLength(10)]
    [FieldTrim(TrimMode.Both)]
    public string TypeControl;

    [FieldFixedLength(3)]
    [FieldTrim(TrimMode.Both)]
    public int Id;

    [FieldFixedLength(3)]
    [FieldTrim(TrimMode.Both)]
    public string Name;
}


public class Type00230J
{
    [FieldFixedLength(10)]
    [FieldTrim(TrimMode.Both)]
    public string TypeControl;

    [FieldFixedLength(3)]
    [FieldTrim(TrimMode.Both)]
    public int Id;

    [FieldFixedLength(1)]
    [FieldTrim(TrimMode.Both)]
    public bool Calculated;
}

如果使用下一个代码提取行,则无法在同一文件中区分Type00007P行和Type00230J行:

public override IEnumerable<Row> Execute(IEnumerable<Row> rows)
{
    using (FileEngine file = FluentFile.For<Type00007P>().From(FilePath))
    {
        foreach (object obj in file)
        {
            yield return Row.FromObject(obj);
        }
    }
}

然后,我如何读取第一个固定字段以获得RowType,然后用正确的类处理整行?

致谢!

1 个答案:

答案 0 :(得分:1)

您可以使用MultiRecordEngine。文档为here

var engine = new MultiRecordEngine(
    typeof(Type00007P),
    typeof(Type00230J));

engine.RecordSelector = new RecordTypeSelector(CustomSelector);

然后定义一个CustomSelector

private Type CustomSelector(MultiRecordEngine engine, string recordLine)
{
    if (recordLine.Length == 0)
        return null;

    if (recordLine.StartsWith("Type00007P")))
        return typeof(Type00007P);
    else
        return typeof(Type00230J);
}