Saturday, April 30, 2022

Entity Framework 6 and HierarchyId

 If you create an Entity Framework 6 EDMX (data model) which contains tables with columns of type hierarchyid then you will get some warnings and the table will arrive in the designer with the offending columns removed. However, you can define and process those types of columns in a strongly-typed manner.

Add NuGet package Microsoft.SqlServer.Types to your project.

Create a partial class that contains the missing hierarchical columns, like this example:

using Microsoft.SqlServer.Types;
:
partial class SomeTable
{
  public SqlHierarchyId SomeNode { get; set; }
}

Unfortunately you can't use LINQ queries on the tables to process rows containing these types of columns. Write some helper methods that use traditional ADO.NET to execute a reader over the table and cast the row-column value to a .NET type like this:

var someNode = (SqlHierarchyId)reader.GetValue(1);
var otherNode = reader.IsDBNull(2) ? SqlHierarchyId.Null : (SqlHierarchyId)reader.GetValue(2)

Note how the second sample line deals with a nullable hierarchyid column.

Thursday, April 21, 2022

Visual Studio 2022 target 4.5

My laptop which has only had Visual Studio 2022 installed and has no history of any other versions being installed will not load projects targeting .NET Framework 4.5. It suggests a download, but no suitable files are available from the Microsoft download pages any more.

Thomas Levesque's instructions for a fix seem dangerous, but after several futile experiments I found that his steps work:

Download the Nuget package Microsoft.NETFramework.ReferenceAssemblies.net45

Rename the following folder (to keep a backup) and replace it with the v4.5 folder unzipped from the NuGet package.

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5

Thereafter VS2022 can open, build and run 4.5 projects. You'll need suitable account permission to rename and replace the folders.