.NET Core 3.1 和 SQL 服务器 hierarchyid - 多个异常

.NET Core 3.1 and SQL Server hierarchyid - multiple exceptions

我在我的 .Net Core 3.1 项目中使用 SQL Server Db,一些存储过程和视图的参数和数据具有 hierarchyid 类型。

我使用 Microsoft.Data.SqlClient 包。当我尝试使用 SqlDataReader 读取数据时,出现异常:

System.IO.FileNotFoundException : Could not load file or assembly 'Microsoft.SqlServer.Types, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'. The system cannot find the file specified.

好的,我尝试按照它的建议使用 Microsoft.SqlServer.Types,但是这个包不是 .NET Standard,它不起作用。

此外,我发现 EntityFrameworkCore.SqlServer.HierarchyId 但是当我使用它时,我得到:

System.InvalidCastException : Unable to cast object of type 'Microsoft.SqlServer.Types.SqlHierarchyId' to type 'Microsoft.Data.SqlClient.Server.IBinarySerialize'.

那么究竟如何才能在 .NET Core 3.1 中使用 HierarchyId 类型呢?

我计划在 linux 上托管此解决方案。

更新

我确实使用与 .NET Core 兼容的 Microsoft.Data.SqlClient 2.0。另外,我添加了 EntityFrameworkCore.SqlServer.HierarchyId,然后出现此错误:

System.InvalidCastException : Unable to cast object of type 'Microsoft.SqlServer.Types.SqlHierarchyId' to type 'Microsoft.Data.SqlClient.Server.IBinarySerialize'.

这是 .csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="EntityFrameworkCore.SqlServer.HierarchyId" Version="1.1.0" />
    <PackageReference Include="Microsoft.Data.SqlClient" Version="2.0.0" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
  </ItemGroup>

  <ItemGroup>
    <Folder Include="Helpers\" />
  </ItemGroup>

</Project>

到目前为止运气不好。

更新 2

这是抛出异常的代码:

using (SqlDataReader reader = await detailsCmd.ExecuteReaderAsync())
{
  while (reader.Read())
  {
    details.Add(new HierarchyDetails
    {
      Id = reader.GetInt32(0),
      groupPath = reader.GetValue(1).ToString(), // <==== EXCEPTION
      name = reader.GetString(2),
      optionalData = reader.IsDBNull(3) ? null : reader.GetString(3)
    });
  }
}

而 table 只有一行:

id  groupPath   culture name    optionalData
24  0x58        en-US   testing 

您的错误消息表明您使用了一些使用 nuget https://www.nuget.org/packages/Microsoft.SqlServer.Types/10.50.1600.1 的东西,它是 .NET Framework dll,而不是 .NET Core。

您提到您使用 Microsoft.Data.SqlClient,请确保您使用与 .NET Core 兼容的 https://www.nuget.org/packages/Microsoft.Data.SqlClient/

如果出现其他错误,请同时检查 Entity Framework Core hierarchyid

目前在所有查询中将 hierarchyid 转换为 NVARCHAR 的解决方案:

... CAST(groupPath as NVARCHAR(4000)) as groupPath ...

然后将其用作字符串。