I managed to achieve what you wanted using the free api aproach. I needed to remove the PreiousId property from the Foo class - it will be added later by matching.
public class Foo { [Key] public virtual int Id { get; set; } public virtual Foo Previous { get; set; } public virtual Foo Next { get; set; } }
Change all your properties to virtual, as this will allow ef to dynamically monitor the state of properties in memory. Then, inside the DbContext derived class, you must override the OnModelCreating method and define the mapping there:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Foo>() .HasOptional(f => f.Next) .WithOptionalPrincipal(f => f.Previous) .Map(c => c.MapKey("PreviousId")); base.OnModelCreating(modelBuilder); }
This will add the Foo table column PreviousId, which will be the foreign key of the relation. He will determine the relationship 1-0. If you assign one Foo object to another previous property, then the assigned object will refer to it in the Next property. I checked it with the following code:
using(MyDbContext context = new MyDbContext("Test")) { context.Database.Delete(); Foo foo1 = context.Foos.Create(); Foo foo2 = context.Foos.Create(); foo1.Next = foo2; context.Foos.Add(foo1); context.Foos.Add(foo2); context.SaveChanges(); } using (MyDbContext context = new MyDbContext("Test")) { Foo foo1 = context.Foos.OrderBy(f => f.Id).First(); Foo foo2 = context.Foos.OrderBy(f => f.Id).Skip(1).First();
mr100
source share