entity-framework-coreentity-framework-migrations

Entity Framework Core 8 and HierarchyId error on add-migration


I have got this error trying to add a new migration while adding a new entity with a HierarchyId property

Unable to create a 'DbContext' of type ''. The exception 'The 'HierarchyId' property 'Node.HierarchyId' could not be mapped to the database type 'hierarchyid' because the database provider does not support mapping 'HierarchyId' properties to 'hierarchyid' columns. Consider mapping to a different database type or converting the property value to a type supported by the database using a value converter. See https://aka.ms/efcore-docs-value-converters for more information. Alternately, exclude the property from the model using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.' was thrown while attempting to create an instance. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728

Code:

builder.Entity<Node>(b => {
        b.ConfigureBaseEntityProperties("Nodes");

        b.HasDiscriminator(c => c.Type)
         .HasValue<RoomNode>(NodeType.Room.ToString())
         .HasValue<EstimateNode>(NodeType.Estimate.ToString())
         .HasValue<FolderNode>(NodeType.Folder.ToString())
         .HasValue<AssignmentNode>(NodeType.Assignment.ToString());

        //Properties
        b.Property(q => q.Name).IsRequired().IsUnicode(false).HasMaxLength(150);
        b.Property(q => q.Type).IsRequired().IsUnicode(false).HasMaxLength(16);
        b.Property(e => e.HierarchyId)
           .HasColumnType("hierarchyid");
});

Configure<AbpDbContextOptions>(options =>
        {
            /* The main point to change your DBMS.
             * See also RestorNetMigrationsDbContextFactory for EF Core tooling. */
            options.UseSqlServer(optionsBuilder =>
            {
                optionsBuilder.UseQuerySplittingBehavior(QuerySplittingBehavior.SingleQuery);
                optionsBuilder.UseHierarchyId();
            });
        });

Solution

  • HierarchyId must be configured in DbContextOptionsBuilder and not DbContextOptions

    public RestorNetDbContext CreateDbContext(string[] args)
        {
            RestorNetEfCoreEntityExtensionMappings.Configure();
    
            var configuration = BuildConfiguration();
    
            var builder = new DbContextOptionsBuilder<RestorNetDbContext>()
            .UseSqlServer(r => {
                configuration.GetConnectionString("Default");
                r.UseHierarchyId();
            });
    
            return new RestorNetDbContext(builder.Options);
        }