简体   繁体   中英

Entity Framework 6 configure model using Fluent API

I have hierarchical model (binary tree).

class Partner
{
     public int ID {get; set; }

     public string Name { get; set; }

     // Parent in the tree.
     public virtual Partner BinarParent {get; set;}  

     // Who is invited partner in tree.
     public virtual Partner Sponsor {get; set;}     

     // Childs partners.
     public virtual List<Partner> Childs {get; set;} 
}

I am having exception now:

Unable to determine the principal end of an association between the types 'Partner' and 'Partner'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

How can i configure navigation properties (Sponsor and Binary Parent) using Fluent API, for this model?

PS

  • Model "Partner" is stored in the table "Partners".
  • If I remove one of the properties (Sponsor or BinaryPartner), an exception is not thrown.

Help me, please.

Do this in your Context:

public class YourContext : DbContext
{
    //...
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       // Configure the primary key for the Partner
       modelBuilder.Entity<Partner>().HasKey(t => t.ID);

       // Map one-to-many relationship
       modelBuilder.Entity<Partner>()
            .HasMany(p => p.Childs)
            .WithOptional(p => p.BinarParent);


        modelBuilder.Entity<Partner>()
            .HasOptional(t => t.Sponsor)
            .WithOptionalDependent()
            .Map(t => t.MapKey("FK_Sponsor_Id"))

    }
    //...
}

The first relationship maps your BinarParent Property with your Collection of Childs. The second relationship map the property Sponsor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM