Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a one to one self reference using Entity Framework Code First

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?

like image 759
mnwsmit Avatar asked Mar 17 '23 11:03

mnwsmit


1 Answers

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);
like image 74
Paul Kyrejto Avatar answered Apr 25 '23 03:04

Paul Kyrejto