4

I want to implement versioning on my entity Stuff. Each entity has an optional reference to the next version (the latest version will be null) and an optional reference to the previous version (the first version will be null). I am using entity framework 6, code first. I tried with the following model and modelbuilder statement (and many variations).

public class Stuff
{
    public int StuffId { get; set; }

    [ForeignKey("NextVersion")]
    public int? NextVersionId { get; set; }
    [InverseProperty("PreviousVersion")]
    public virtual Stuff NextVersion { get; set; }

    public virtual Stuff PreviousVersion { get; set; }
}

modelBuilder.Entity<Stuff>().HasOptional(t => t.NextVersion).WithOptionalDependent(t => t.PreviousVersion);

However in this case the [ForeignKey("NextVersion")] is ignored and a foreign key NextVersion_StuffId is generated. How can I instruct EF to use the property NextVersionId as the foreign key?

mnwsmit
  • 1,198
  • 2
  • 15
  • 31
  • ForeignKey is being used incorrectly. All else the same, I believe putting [ForeignKey("NextVersionId")] above NextVersion would be a step in the right direction, and may be all you need. – npjohns Mar 21 '16 at 23:42

1 Answers1

7
public class Stuff
{
    public int Id { get; set; }

    public int? NextVersionId { get; set; }

    public int? PrevVersionId { get; set; }

    public virtual Stuff NextVersion { get; set; }

    public virtual Stuff PrevVersion { get; set; }

}

Updated:

modelBuilder.Entity<Stuff>().HasOptional(t => t.NextVersion).WithMany().HasForeignKey(t => t.NextVersionId);
modelBuilder.Entity<Stuff>().HasOptional(t => t.PrevVersion).WithMany().HasForeignKey(t => t.PrevVersionId);
Paul Kyrejto
  • 1,285
  • 3
  • 12
  • 19
  • 1
    Error: Unable to determine the principal end of an association between the types 'ReizenInDeTijd.Model.Entities.Stuff' and 'ReizenInDeTijd.Model.Entities.Stuff'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations. – mnwsmit Apr 10 '15 at 11:11
  • Besides, if possible I would prefer there to be one foreign key column on the database (but this is less important than making it just work ;-) – mnwsmit Apr 10 '15 at 11:12
  • Updated answer. Either you have just one way linked list (Prev OR Next) and single FK or two ways list (Prev AND Next) and 2 FKs – Paul Kyrejto Apr 10 '15 at 11:35
  • It now works. It does have two foreign keys but that will do for now. Thank you! – mnwsmit Apr 10 '15 at 11:48