无法确定导航属性表示的与枚举类型实体的关系



我有一个.Net Core 3.1 web项目,它有一个对Enum类型实体(Status(的实体(Process(引用。它是以这种方式设置的,以便由无状态工作流用于处理程序中进程状态的更改。在运行时,它在这一行失败,并显示上面的异常消息:

processes = await _dbContext.Process.ToListAsync();

完整的异常消息:

'Unable to determine the relationship represented by navigation property 'Process.Status' of type 'Status'. 
Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.'

以下是模型和数据库上下文代码:

public enum StatusID : int
{
[Display(Name = "Draft")]
Draft = 1,
[Display(Name ="In Review")]
InReview = 2,
[Display(Name = "Approved")]
Inactive = 3
}
[Table("Status", Schema = "Industrial")]
public class Status
{
private Status() { }
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public StatusID StatusID { get; private set; }
[StringLength(50)]
public string Name { get; private set; }
}
[Table("Process", Schema = "Industrial")]
public partial class Process
{
[Key]
public int ProcessID { get; set; }
public StatusID StatusID { get; set; } = StatusID.Draft;
[ForeignKey("StatusID")]
public virtual Status Status { get; private set; }
}
public class DbContext
{
public DbSet<Process> Process { get; set; }
public DbSet<Status> Status { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Entity<Status>().HasNoKey().Property(c => c.StatusID)
.HasConversion(
v => v.ToString().ToLowerInvariant(),
v => (StatusID)Enum.Parse(typeof(StatusID), v, true)
)
.HasColumnName("GeneralName")
.IsUnicode(false);
}
}

我在这里搜索了其他帖子,许多人建议在DbContext中的OnModelCreating方法中设置导航定义,我尝试了一些变体,但都失败了。以下是我尝试过的几个:

modelBuilder.Entity<Process>()
.HasOne("Status", "Status")
.WithOne("Status");

modelBuilder.Entity<Process>()
.HasOne(p => p.Status)
.WithOne()
.HasForeignKey<Status>(m => m.StatusID)
.OnDelete(DeleteBehavior.Restrict);

我发现了这个问题的根本原因,这是因为我的数据库表生成脚本在外键创建语句中出错,应该如下所示:

ALTER TABLE [Industrial].[Process]  WITH CHECK ADD  CONSTRAINT [FK_Process_Status_StatusID] FOREIGN KEY([StatusID])
REFERENCES [Industrial].[Status] ([StatusID])

我的是[FK_Process_Status],而不是[FK_Process_Status_StatusID]

这是在Microsoft SQL Server中。

相关内容

  • 没有找到相关文章

最新更新