我有以下课程:
public class Application
{
public int Id { get; set; }
/* Other properties */
public int LegacyId { get; set; }
public int LegacyParentId { get; set; }
public int? ApplicationSupersessionId { get; set; }
public virtual ICollection<Application> ApplicationSupersessions { get; set; }
public Application()
{
ApplicationSupersessions = new List<Application>();
}
}
ApplicationSupersessions
是可选的自联接实体。我已将数据添加到我的Applications
表中,并且我尝试调整数据,目前看起来像这样:
但是我需要应用5413
和5414
来获得ApplicationSupersessionId
5415
,就像我们的传统系统中的情况一样,因此我添加了2 Legacy
列
所以我尝试了以下内容:
var applications = CatalogueContext.Applications.ToList();
foreach (var application in applications)
{
var legacyChildren = applications.Where(x =>
x.LegacyParentId == application.LegacyId).ToList();
if(legacyChildren.Any())
{
foreach(var child in legacyChildren)
{
application.ApplicationSupersessions.Add(child);
}
CatalogueContext.Entry(application).State = EntityState.Modified;
}
}
CatalogueContext.SaveChanges();
但我在CatalogueContext.Entry(application).State = EntityState.Modified;
行上收到以下错误:
答案 0 :(得分:1)
我设法解决了这个问题。我在配置中设置了错误的关系。
我有这个:
HasOptional(x => x.ApplicationSupersessions)
.WithMany()
.HasForeignKey(x => x.ApplicationSupersessionId)
.WillCascadeOnDelete(false);
应该是这样的:
HasMany(x => x.ApplicationSupersessions)
.WithOptional()
.HasForeignKey(x => x.ApplicationSupersessionId)
.WillCascadeOnDelete(false);
我不确定它的差异是什么以及它是否是一个EF错误?