实体框架:自连接错误

时间:2014-06-03 14:00:28

标签: entity-framework entity-framework-6

我有以下课程:

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表中,并且我尝试调整数据,目前看起来像这样:

enter image description here

但是我需要应用54135414来获得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;行上收到以下错误:

enter image description here

1 个答案:

答案 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错误?

相关问题