实体框架核心等级

时间:2018-05-29 23:36:15

标签: entity-framework entity-framework-core

我正在尝试使用EF Core,但我需要在其中一个表上使用sql server数据类型hierarchyid

是否可以将c#类中的字段指定为hierarchyid类型?

我可以手动将EF列创建为hierarchyid,而不会破坏EF吗?

编辑: 我试过这样做:

public class Entity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public SqlHierarchyId HierarchyId { get; set; }
}

由于建议EF核心2.1支持此功能,但是当我运行add-migration时出现此错误:

The current CSharpHelper cannot scaffold literals of type 'Microsoft.SqlServer.Types.SqlHierarchyId'. Configure your services to use one that can.

3 个答案:

答案 0 :(得分:5)

如果使用的是Entity Framework Core 3.1,则应使用NuGet EntityFrameworkCore.SqlServer.HierarchyId。 .NET Core不完全支持Microsoft.SqlServer.Types

https://www.nuget.org/packages/EntityFrameworkCore.SqlServer.HierarchyId

https://github.com/dotnet/efcore/issues/365#issuecomment-618688829

EntityFrameworkCore.SqlServer.HierarchyId由@bricelam撰写,该实体与Entity Framework团队合作,但需要注意的是,此NuGet仍然是不受支持的第三方软件包。

我认为这仍然是您最好的选择,因为它不会很快实施,并且可能永远不会得到官方的支持。 2020-04-07的评论:

基本上,我们的小型团队实施起来似乎并不明智, 现在支持并维护.NET的HierarchyId库,因此 我们被有效地阻止了这一点。

https://github.com/dotnet/efcore/issues/365#issuecomment-610586190

答案 1 :(得分:4)

对于那些寻找SqlHierarchyId程序包所在的Nuget程序包的人来说,它位于Microsoft.SqlServer.Types中。

请注意,程序包信息表示此程序包包含DbGeography和DbGeometery类型,但也包含SqlHierarchyId类型。

还要注意,类是SqlHierarchyId,而不是HierarchyId(就像我一直在寻找的那样)。

答案 2 :(得分:0)

目前还没有很好的本机支持,但是自19/25/19起,我发现最好的方法是使用nuget软件包dotMorten.Microsoft.SqlServer.Types而不是Microsoft.SqlServer.Types,因为{{ 1}}与Core不完全兼容。

这是dotMorten的最小工作代码示例,用于生成带有hierarachyId的表

请注意,使用的仍然是Microsoft.SqlServer.Types,dotMortan使用相同的名称空间来代替它。

Microsoft.SqlServer.Types

现在using Microsoft.EntityFrameworkCore; using Microsoft.SqlServer.Types; namespace ConsoleApp1 { public class Db : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true"); } } public DbSet<Person> People { get; set; } } public class Person { public int Id { get; set; } public SqlHierarchyId HId { get; set; } public string Name { get; set; } } } add-migrations将可以正常工作并适当地生成表,但是,诸如此类:

update-database 仍然不起作用,我也无法找到解决方法。