首页 > 解决方案 > 处理映射器属性中的空值

问题描述

我正在尝试读取一个平面文件并执行一些过程。为此,我定义了一个映射器。该映射器将为每个属性分配值。在文档中,日期将用yyMMdd格式表示,它可以有“ ”或000000空值。这意味着,如果日期是 6 个零或 6 个空格,则输出应为空。我试图通过定义 NullFormater 来做到这一点。但是没有用。

这是我尝试过的:

==============================

public class Test : DocumentRecordBase
{
public string StorageOrganisation { get; set; }
public Guid? StorageOrganisationId { get; set; }
public string StorageDescription { get; set; }
public DateTime? PaymentDueDate { get; set; }
public decimal? DiscountRate { get; set; }
public int? MaximumDaysDiscount { get; set; }
public DateTime? DateStorageChargeCommences { get; set; }
public decimal? StorageChargePerBalePerDay { get; set; }
public decimal? PenaltyInterestRate { get; set; }
public DateTime? LotAvailableDate { get; set; }
public decimal? PostSaleRechargeRebate { get; set; }

public Test() : base()
{
}

    public override T GetDocumentRecord<T>()
    {
        if (typeof(T) == typeof(Test))
        {
            return this as T;
        }
        return null;
    }


    public static IFixedLengthTypeMapper<Test> GetMapper()
    {
        var mapper = FixedLengthTypeMapper.Define<Test>();
        mapper.Property(r => r.RecordType, 2);
        mapper.Property(r => r.RecordSubType, 1);

        mapper.Property(r => r.PaymentDueDate, 6)
            .ColumnName("PaymentDueDate")
            .InputFormat("yyMMdd")
            .NullFormatter(NullFormatter.ForValue("000000")); // if the read value is "000000" or "      " then should pass as null


        mapper.CustomMapping(new RecordNumberColumn("RecordNumber")
        {
            IncludeSchema = true,
            IncludeSkippedRecords = true
        }, 0).WithReader(r => r.RecordNumber);
        return mapper;
    }

    public static bool GetMapperPredicate(string x)
    {
        return x.StartsWith("11A");
    }

}

标签: c#nullautomapperflat-filefixed-length-file

解决方案


根据 NullFormatter 的定义,(在此处找到),您只能分配 1 个固定值。“如果是固定值,可以使用 NullFormatter.ForValue 方法。”

NullFormatter = NullFormatter.ForValue("NULL") 

如果您使用“000000”,那么它应该将 000000 转换为 null,否则,空格将被视为实际值。任意数量的 0 != 6 也将产生非空值。

另外,请定义“但没有用”的意思。请提供详细信息和错误以进行详细说明


推荐阅读