我正在创建一个可以将.csv文件导入SQL数据库的应用程序。 .csv文件被读入7列:Id,InvoiceAmount,InvoiceDate,InvoiceNumber,DeniedDate,DeniedReasonId和DeniedNotes。 .csv中的每一行都有一个Id,但下一个六个字段中只有三个将被填充。 InvoiceAmount,InvoiceDate,InvoiceNumber OR DeniedDate,DeniedReasonId,DeniedNotes。
[Table("TemporaryCsvUpload")]
public class OutstandingCredit
{
[CsvColumn(FieldIndex = 1, CanBeNull = false)]
public string Id { get; set; }
[CsvColumn(FieldIndex = 2, OutputFormat = "dd MMM HH:mm:ss")]
public DateTime InvoiceDate { get; set; }
[CsvColumn(FieldIndex = 3)]
public string InvoiceNumber { get; set; }
[CsvColumn(FieldIndex = 4, OutputFormat = "C")]
public decimal InvoiceAmount { get; set; }
[CsvColumn(FieldIndex = 5, OutputFormat = "dd MMM HH:mm:ss")]
public DateTime DeniedDate { get; set; }
[CsvColumn(FieldIndex = 6)]
public int DeniedReasonId { get; set; }
[CsvColumn(FieldIndex = 7)]
public string DeniedNotes { get; set; }
}
所以问题就出现了:在.csv的每一行中,InvoiceDate或DeniedDate都是空的。发生这种情况时,我希望数据库中的相应字段保持为空。但相反,它是默认为1/1/0001 12:00。另外,当.csv中DeniedReasonId为空时,它默认为0.我试图保持null而不是默认值。
这是我使用LinqToCsv以.csv形式循环值的地方:
var cc = new CsvContext();
var filePath = uploadFile(csvFile.InputStream);
var model = cc.Read<OutstandingCredit>(filePath, inputFileDescription);
try
{
var entity = new ManagementEntities();
foreach (var item in model)
{
var tc = new TemporaryCsvUpload
{
Id = item.Id,
InvoiceAmount = item.InvoiceAmount,
InvoiceDate = item.InvoiceDate,
InvoiceNumber = item.InvoiceNumber,
DeniedDate = item.DeniedDate,
DeniedReasonId = item.DeniedReasonId,
DeniedNotes = item.DeniedNotes
};
entity.TemporaryCsvUploads.Add(tc);
任何帮助将不胜感激。谢谢!
答案 0 :(得分:0)
如果您希望CSV文件中的空值转换为null
,则必须将您的属性更改为Nullable
种类型DateTime?
,decimal?
和{{1 }})。您目前看到1/1/0001 12:00 AM和0的原因是因为这些是int?
和DateTime
的默认值。通过将其更改为int
类型,默认值将更改为Nullable
(或者更确切地说,更改为null
,其中Nullable<T>
为false,但C#基本上将其视为{ {1}})。
HasValue
如果null
中的相应类型尚未[Table("TemporaryCsvUpload")]
public class OutstandingCredit
{
[CsvColumn(FieldIndex = 1, CanBeNull = false)]
public string Id { get; set; }
[CsvColumn(FieldIndex = 2, OutputFormat = "dd MMM HH:mm:ss")]
public DateTime? InvoiceDate { get; set; }
[CsvColumn(FieldIndex = 3)]
public string InvoiceNumber { get; set; }
[CsvColumn(FieldIndex = 4, OutputFormat = "C")]
public decimal? InvoiceAmount { get; set; }
[CsvColumn(FieldIndex = 5, OutputFormat = "dd MMM HH:mm:ss")]
public DateTime? DeniedDate { get; set; }
[CsvColumn(FieldIndex = 6)]
public int? DeniedReasonId { get; set; }
[CsvColumn(FieldIndex = 7)]
public string DeniedNotes { get; set; }
}
,则还必须确保TemporaryCsvUpload
。