【问题标题】:Remove the timestamp from a map in C#从 C# 中的地图中删除时间戳
【发布时间】:2020-01-10 17:01:28
【问题描述】:

我在尝试从地图中删除时间戳时遇到错误,我想知道是否有任何方法可以做到这一点?

AutoMap();
Map(m => m.BeginDate.Value.ToShortDateString()).Name("Delivery Begin Date").Index(0);

我收到错误:

System.InvalidOperationException
  HResult=0x80131509
  Message=No members were found in expression '{expression}'.
  Source=CsvHelper
  StackTrace:
   at CsvHelper.Configuration.ClassMap`1.Map[TMember](Expression`1 expression, Boolean useExistingMap)
   at Cgb.Grain.Customer.Service.Csv.BidsheetCsvMap..ctor() in C:\Users\larkb\Source\Repos\GrainCustomer\GrainCustomerService\Csv\BidsheetCsvMap.cs:line 33
   at Cgb.Grain.Customer.Service.CsvExport.<>c.<.ctor>b__1_5() in C:\Users\larkb\Source\Repos\GrainCustomer\GrainCustomerService\Csv\CsvExport.cs:line 27
   at Cgb.Grain.Customer.Service.CsvExport.WriteCsvToMemory[T](IEnumerable`1 items) in C:\Users\larkb\Source\Repos\GrainCustomer\GrainCustomerService\Csv\CsvExport.cs:line 40
   at GrainCustomerService.Controllers.BidsheetController.GetBidsheetsAsCsv(Nullable`1 accountId) in C:\Users\larkb\Source\Repos\GrainCustomer\GrainCustomerService\Controllers\BidsheetController.cs:line 118
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()

【问题讨论】:

  • automap 标签是用于插值空间数据的 R 包。
  • 如果没有属性,为什么还需要地图?
  • 我刚刚给出了一个完整 ClassMap 的代码 sn-p
  • 如果您添加更多关于您正在使用的库以及您正在尝试做什么的上下文,您可能会收到更多回复。
  • @simplest 我在问题中看不到 full sn-p。理想情况下,我们需要minimal reproducible example

标签: c# datetime csvhelper


【解决方案1】:

正如错误消息所说,Map() 方法只希望在表达式中接收您的类的成员。您必须将日期的格式移动到ConvertUsing()

public class Program
{
    public static void Main(string[] args)
    {
        var records = new List<Foo> { new Foo { Id = 1, BeginDate = DateTime.Now } };

        using(var csv = new CsvWriter(Console.Out))
        {
            csv.Configuration.RegisterClassMap<FooMap>();
            csv.WriteRecords(records);
        }

        Console.ReadLine();
    }
}

public class Foo
{
    public int Id { get; set; }
    public DateTime BeginDate { get; set; }
}

public class FooMap : ClassMap<Foo>
{
    public FooMap()
    {
        AutoMap();
        Map(m => m.BeginDate).Name("Delivery Begin Date").Index(0).ConvertUsing(x => x.BeginDate.ToShortDateString());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2018-06-27
    • 1970-01-01
    • 2013-08-22
    • 2012-06-28
    • 2016-08-31
    相关资源
    最近更新 更多