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

Versioning is something I want to use with my entity Stuff. The latest version of each entity will be null, and each entity has an optional reference to the preceding version (the first version will be null). Entity Framework 6 is what I'm using. I made an attempt using the next 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);

The [ForeignKey("NextVersion")] is disregarded in this instance, and a foreign key called NextVersion StuffId is created instead. How can I tell EF to utilize the NextVersionId attribute 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