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

c# entity-framework entity-framework-6 foreign-keys self-reference

Question

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?

1
4
4/10/2015 10:32:04 AM

Accepted Answer

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);
6
4/10/2015 11:32:15 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow