Question

I have an entity which has a self reference such that a Member can have a Witness who has to be a member and may also have a Reference who has to be a member. I modeled this as follows;

public class Member
    {
        public int Id { get; set; }

        //omitted for brevity
        public int? WitnessId { get; set; }
        public virtual Member Witness { get; set; }

        public int? ReferenceId { get; set; }
        public virtual Member Reference { get; set; }
    }

When I run the update-database on package manager console, I get the following error: "XXX.Client.Entities.Member' and 'XXX.Client.Entities.Member'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations."

Any idea on how this can be resolved?

Was it helpful?

Solution

Try to define relationship with fluent api this way (works for me):

        modelBuilder.Entity<Member>().HasKey(x => x.Id);
        modelBuilder.Entity<Member>().HasOptional(x => x.Witness)
            .WithMany()
            .HasForeignKey(m => m.WitnessId);
        modelBuilder.Entity<Member>().HasOptional(x => x.Reference)
            .WithMany()
            .HasForeignKey(m => m.ReferenceId);

OTHER TIPS

This looks to be working:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {


        modelBuilder.Entity<Member>().
            HasOptional(e => e.Witness).
            WithMany().
            HasForeignKey(m => m.WitnessID);

        modelBuilder.Entity<Member>().
            HasOptional(e => e.Reference).
            WithMany().
            HasForeignKey(m => m.ReferenceID);

        base.OnModelCreating(modelBuilder);

    }

This will also work for those of us who prefer to have things in the class deriving from the EntityTypeConfiguration

class MemberEntityConfiguration : EntityTypeConfiguration<Member>
{
    public MemberEntityConfiguration()
    {
        HasKey(x => x.Id);
        HasOptional(x => x.Witness).WithMany().HasForeignKey(m => m.WitnessId);
        HasOptional(x => x.Reference).WithMany().HasForeignKey(m => m.ReferenceId);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top