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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With