C# EF核心未保存ParentId
我试图建立一个“工作”对象的结构。这些用于描述一个人需要完成的整个过程 比如说 如果这项工作有“煮咖啡”的描述,那么它会有一份其他工作的清单,当这些工作一起完成时,就会产生煮咖啡的效果 一个示例结构可能是:C# EF核心未保存ParentId,c#,entity-framework-core,C#,Entity Framework Core,我试图建立一个“工作”对象的结构。这些用于描述一个人需要完成的整个过程 比如说 如果这项工作有“煮咖啡”的描述,那么它会有一份其他工作的清单,当这些工作一起完成时,就会产生煮咖啡的效果 一个示例结构可能是: Make Coffee |- Boil Kettle |- Fill Kettle |- Turn on Kettle |- Get a cup |- Place instant coffee in the cup |- Pour boiling wate
Make Coffee
|- Boil Kettle
|- Fill Kettle
|- Turn on Kettle
|- Get a cup
|- Place instant coffee in the cup
|- Pour boiling water in the cup
|- Add milk to the cup
还应注意,每个作业都有一个版本号;和版本FID。这是在需要更改作业的情况下,只有一个版本是“实时”的,并且是将要使用的版本
我正在向EF Core DBContext添加对象,在调用SaveChanges之前,我可以正确地看到结构;但是,一旦关闭/重新加载上下文,作业就不再相互引用。我可以在SQLManagementStudio中看到,所有对象的ParentID都为null
职位类别如下:
public class Job
{
public int JobId { get; set; }
[Required]
public string Description { get; set; }
public string Code { get; set; }
public int Quantity { get; set; } = 1;
public int Time { get; set; }
public TimeUnit UnitOfTime { get; set; }
[ForeignKey("VersionOf")]
public int? VersionOfId { get; set; }
public virtual Job VersionOf { get; set; }
public int JobVersion { get; set; } = 1;
[ForeignKey("Parent")]
public int? ParentId { get; set; }
public virtual Job Parent { get; set; }
public virtual List<Job> Jobs { get; set; } = new List<Job>();
public void AddJob(Job job)
{
job.Parent = this;
Jobs.Add(job);
}
}
public enum TimeUnit
{
Seconds,
Minutes,
Hours,
Days,
Weeks,
Months,
Years
}
您可以在此处查看表格的外观:
我想这可能是懒散加载的todo,我已经启用了:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"<--snip-->");
optionsBuilder.UseLazyLoadingProxies();
}
protectedoverride void onconfiguration(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@“”);
optionsBuilder.UseLazyLoadingProxies();
}
然而,我已经删除了这个,这个问题还在继续
有人知道如何解决这个问题吗?您缺少
家长的分配
Job PK4 = new Job()
{
Code = "PK4",
Description = "Pick Item",
Time = 15,
UnitOfTime = TimeUnit.Seconds,
Parent = PK3 //add this line!
};
是正确的,问题是EF Core根本不知道如何处理这两个外键。将以下内容添加到OnModelCreating中已为我解决了此问题
我不确定这是否是一种“正确”的方法,但它对我来说是有效的
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Job>().HasOne(j => j.Parent);
modelBuilder.Entity<Job>().HasOne(j => j.VersionOf);
}
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
modelBuilder.Entity().HasOne(j=>j.Parent);
modelBuilder.Entity().HasOne(j=>j.VersionOf);
}
我看不到您在哪里设置导航属性或外键属性。您还需要配置导航属性与其反向属性之间的链接。在添加版本控制内容之前,您可能希望只处理父/子关系。我不完全确定您的意思。我有另一个类似的对象,它有一个父对象和一个相同类型的列表,它是开箱即用的。你是对的,删除版本修复了这个问题。但是,对于我的用例,我确实需要同一作业的多个版本(只需非常小的编辑),而不是。AddJob()为我做这件事。(错误地编辑了您的评论;对不起!)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Job>().HasOne(j => j.Parent);
modelBuilder.Entity<Job>().HasOne(j => j.VersionOf);
}