Entity Framework: Self-join error
-
21-12-2019 - |
Question
I have the following class:
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>();
}
}
Where ApplicationSupersessions
is an optional self-joined entity. I have data already added to my Applications
table and I'm trying to adjust the data, which currently looks like this:
But I need Applications 5413
and 5414
to have an ApplicationSupersessionId
of 5415
as that is what it looks like in our Legacy system, hence why I have added the 2 Legacy
columns
So I've tried the following:
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();
But I get the following error on the line CatalogueContext.Entry(application).State = EntityState.Modified;
:
Solution
I managed to solve this. I had the relationship set up wrong in my Configuration.
I had this:
HasOptional(x => x.ApplicationSupersessions)
.WithMany()
.HasForeignKey(x => x.ApplicationSupersessionId)
.WillCascadeOnDelete(false);
When it should have been this:
HasMany(x => x.ApplicationSupersessions)
.WithOptional()
.HasForeignKey(x => x.ApplicationSupersessionId)
.WillCascadeOnDelete(false);
I'm not sure what the difference is and whether or not its an EF bug?