I am trying to set up a realationship between an object and versions of the same object. I am using EFCore and its saving the ID from one of the objects into both fields.
My objects are as follows:
public class Workflow
{
public int WorkflowId { get; set; }
[ForeignKey("Parent")]
public int? ParentId { get; set; }
public virtual Workflow Parent { get; set; }
public virtual List<Workflow> Workflows { get; set; } = new List<Workflow>();
public int InternalSequence { get; set; }
public decimal Quantity { get; set; }
public virtual List<WorkflowVersionLink> VersionLinks { get; set; } = new List<WorkflowVersionLink>();
}
public class WorkflowVersionLink
{
public int WorkflowVersionLinkId { get; set; }
public int? IsVersionOfId { get; set; }
public virtual Workflow IsVersionOf { get; set; }
public int? VersionId { get; set; }
public virtual Workflow Version { get; set; }
public bool IsLive { get; set; }
}
And I am setting up the OnModelCreating as follows:
//All of my attempts have used this:
modelBuilder.Entity<WorkflowVersionLink>()
.HasKey(t => new { t.IsVersionOfId, t.VersionId });
//Attempt one: No manual configuration
//Attempt two:
modelBuilder.Entity<WorkflowVersionLink>()
.HasOne(lk => lk.Version)
.WithMany(wf => wf.VersionLinks)
.HasForeignKey(lk => lk.VersionId);
//Attempt three (following info from SO):
modelBuilder.Entity<WorkflowVersionLink>()
.HasOne(lk => lk.IsVersionOf)
.WithMany()
.HasForeignKey(lk => lk.IsVersionOfId)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<WorkflowVersionLink>()
.HasOne(lk => lk.Version)
.WithMany(wf => wf.VersionLinks)
.HasForeignKey(lk => lk.VersionId);
I have already tried the approach here: Many-to-many self referencing relationship & the other approaches mentioned above.
I am open to changing to structure, before all of this I didn't use the WorkflowVersionLink Object, and just had a List Versions, however this failed also because I already have a list of child workflows (which I need to keep)
As you can see, I have attempted to fix this issue myself, but I am now stuck and decided to turn to StackOverflow.
You can see the database result here: (I am 100% sure I added two brand new objects that didnt have IDs each time I ran the code) database result
What am I doing wrong here?
Thanks