首页 > 解决方案 > 如何让 AllowDBNull 为 GUID 工作?

问题描述

我正在使用 DataColumn 为 DataTable 创建一个新列。我AllowDBNull用来指定一列可以有 NULL 值。

这很好用,除非我有一个uniqueidentifier我正在做的类型的列

public static Type GetClrType(SqlDbType sqlType, bool isNullable)
{
  switch (sqlType)
  {
     case SqlDbType.UniqueIdentifier:
        return isNullable ? typeof(Guid?) : typeof(Guid);
     ......other types......
  }
}
DataColumn columnValue = DataColumn(column.Name, GetClrType(columnType, IsNullable))
dt.Columns.Add(columnValue);

我在尝试使用CsvHelper加载数据表并看到错误时遇到问题

未处理的异常。System.AggregateException:发生一个或多个错误。(Guid 应包含 32 位数字和 4 个破折号 (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)。无法存储<NULL>在 MyGuIdColumn 列中。预期类型为 Guid。)

任何解决此问题的帮助表示赞赏。

更新(更多细节):

CSV 文件记录是这样的:

Id (uniqueidentifier, Not null)      | Name (Nvarchar, null) | OtherId (uniqueidentifier, null) 
deb01846-c208-ec01-a4e4-005056bc1234 | TestName              | NULL

我正在阅读这样的csv文件:

var dt = new DataTable();
// get the table def -> will have all column props
foreach (column in columns)
{
  var columnType = column.DataType; // (uniqueidentifier) I get this value from table schema
  var dataType = Map.GetClrType(columnType); // (GUID) from a SqlDbType -> c# map
  DataColumn columnValue = new DataColumn(column.Name, dataType);
  columnValue.AllowDBNull = true; // comes from IS Nullable column of table schema
  columnValue.DefaultValue = if is nullable => Guid.Empty/Null/DbNUll.Value; // tried these
  dt.Columns.Add(columnValue);
}

using (var reader = new StreamReader(filePath))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
   using (var dr = new CsvDataReader(csv))
   {
      dt.Load(dr); // error here
      return dt;
    }
}

标签: c#bulkinsertsqlbulkcopycsvhelper

解决方案


哦.. 我花了一段时间才看到它,但问题是,我怀疑您的 CSV 文件实际上包含"NULL"OtherId 列中的字符串;你必须告诉 CSVH “NULL”意味着DBNull.Value

以下代码将读取您发布到 github 的 CSV:

        using var reader = new CsvReader(File.OpenText(_openFileDialog.FileName), conf);
        using var dataReader = new CsvDataReader(reader);

        var dt = dataReader.GetSchemaTable(); //the schema table is huge, get CSVH to make it

        //the schema table describes the file layout
        dt.Rows[0]["DataType"] = typeof(Guid); //first column is a GUID
        dt.Rows[0]["AllowDBNull"] = false;     //and not null (default true)
        dt.Rows[2]["DataType"] = typeof(Guid); //third column is also a GUID

        //tell CSVH that a string of "NULL" is a null value
        var tco = new CsvHelper.TypeConversion.TypeConverterOptions();
        tco.NullValues.Add("NULL");
        reader.Context.TypeConverterOptionsCache.AddOptions<string>(tco);


        var ddt = new DataTable();
        ddt.Load(dataReader);

现在 ddt 包含 OtherId 的 Guid 列,它允许空 guid

您不必事先知道列类型。到该var dt = dataReader.GetSchemaTable();var dt = dataReader.GetSchemaTable();行执行时,dt将具有列名。如果标题与您发布的一样,那么当您获得架构时,但在您读取任何数据之前,您将能够枚举架构表并对其进行调整:

在此处输入图像描述

ps; 我对你的 CSV 有点作弊,因为我懒得查找如何将管道设置为分隔符 - 读者练习(哈哈):

在此处输入图像描述


推荐阅读