gpt4 book ai didi

c# - Entity Framework 6.1.3 层次结构 id 不工作

转载 作者:太空宇宙 更新时间:2023-11-03 12:28:35 28 4
gpt4 key购买 nike

我正在尝试将 SQL Server HierarchyId 数据类型与 Entity Framework 一起使用。由于 Entity Framework 不支持 HierarchyId 数据类型,我正在使用具有 hierarchyid 支持的 Entity Framework 分支: https://entityframework.codeplex.com/SourceControl/network/forks/zgabi/EfHierarchyId/latest

数据库表如下:

CREATE TABLE OrgStructure(
[Id] [hierarchyid] NOT NULL,
[Level] AS ([Id].[GetLevel]()),
[NodeId] [int] IDENTITY(1,1) NOT NULL,
[Title] [varchar](50) NULL)

使用 HierarchyId 数据类型的我的实体定义如下:

public class OrgStructure
{
public HierarchyId Id { get; set; }
public Nullable<int> Level { get; set; }
public int NodeId { get; set; }
public string Title { get; set; }
}

EntityFramework 映射配置定义为:

public class OrgStructureMapping: EntityTypeConfiguration<OrgStructure>
{
public OrgStructureMapping()
{
// Primary Key
this.HasKey(t => t.Id);

// Properties
this.Property(t => t.Id)
.HasColumnType("hierarchyId")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

this.Property(t => t.NodeId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

this.Property(t => t.Title)
.HasMaxLength(50);

// Table & Column Mappings
this.ToTable("OrgStructure");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.Level).HasColumnName("Level");
this.Property(t => t.NodeId).HasColumnName("NodeId");
this.Property(t => t.Title).HasColumnName("Title");
}
}

DBContext如下:

public partial class VisibilityHierarchyDBContext : DbContext
{

public virtual DbSet<OrgStructure> OrgStructure { get; set; }

public VisibilityHierarchyDBContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new OrgStructureMapping());
}
}

在startup.cs中注册DbContext如下

public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<VisibilityHierarchyDBContext>((s) => new VisibilityHierarchyDBContext(Configuration.GetConnectionString("VisibilityDB")));

// Add framework services.
services.AddMvc();
}

使用 DBContext 如下:

public class HomeController : Controller
{
VisibilityHierarchyDBContext context;
public HomeController(VisibilityHierarchyDBContext context)
{
this.context = context;
}
public IActionResult Index()
{
var o = context.OrgStructure.Take(5).ToList(); /* Exception is thrown here */

return View();
}
}

我在上面显示的索引操作中遇到以下错误:

The 'Id' property on 'OrgStructure' could not be set to a 'Microsoft.SqlServer.Types.SqlHierarchyId' value. You must set this property to a non-null value of type 'System.Data.Entity.Hierarchy.HierarchyId'.

非常感谢解决此错误的任何帮助。

最佳答案

我想通了。实际上错误信息有点误导。当我从实体定义和映射中删除“级别”属性时,它就像魅力一样工作。它被打破是因为 Level 列被定义为自动选择 smallint 作为数据类型的计算列,而在实体定义中它的类型是 int。

关于c# - Entity Framework 6.1.3 层次结构 id 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43643481/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com