Skip to content

HierarchyId

Simon Hughes edited this page Dec 30, 2024 · 18 revisions

.NET Core 5 & 6

If any of your tables use the SQL HIERARCHYID type, please install the following package:

Install-Package EntityFrameworkCore.SqlServer.HierarchyId

Also include the .UseHierarchyId() in your connection string options:

var optionsBuilder = new DbContextOptionsBuilder<TestDbContext>()
    .UseSqlServer(@"Data Source=(local);Initial Catalog=test;Integrated Security=True;Encrypt=false;TrustServerCertificate=true",
        x => x
            .UseNetTopologySuite()
            .UseHierarchyId() // <<--- Add this
            .MaxBatchSize(100));

using var db = new TestDbContext(optionsBuilder.Options);

Another example using a connection string from a ConfigurationBuilder:

var configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", false, false)
    .Build();

var conn = configuration.GetConnectionString("EfCoreDatabase");

var optionsBuilder = new DbContextOptionsBuilder<EfCoreDbContext>()
    .UseSqlServer(conn, x => x
        .UseNetTopologySuite()
        .UseHierarchyId());

using var db = new EfCoreDbContext(optionsBuilder.Options);

.NET Core 2 & 3

If any of your tables use the SQL HIERARCHYID type, please install the following package:

Install-Package dotMorten.Microsoft.SqlServer.Types

Please don't use the Microsoft.SqlServer.Types package as this is not yet compatible with .Net Core. Read more here.

EF 6

Now natively supported in the latest version of EntityFramework NuGet package.

Here is an old demo of the AdventureWorks 2012 and 2014 databases which makes use of the HIERARCHYID type within the NuGet Package EntityFrameworkWithHierarchyId (which is now not required anymore): AdventureWorksDemo.zip

Using both HeirarchyId and Table-valued functions

My thanks to Miguel Vrolijk for the following info:

One issue that I’ve encountered is that you can’t use both HierarchyId columns and Table-valued functions as is. You need to compile the CodeFirstStoreFunctions library with the EntityFrameworkWithHierarchyId library instead of the EntityFramework library; the version on NuGet was compiled with the latter.

EF6 v6.3 to have native support for HeirarchyId

My thanks to @sPhinX-LHJ for the following info:

Good news. EF6 support HierarchyId has been added by Gábor Zavarkó on 10 Aug 2018, see here. It's not been released yet on NuGet. However, you can have it now if you grab the source code and compile it yourself.

Clone this wiki locally