Unable to determine the principle end of an association

可紊 提交于 2019-12-02 04:02:08
Colin

You define the principal when you map:

modelBuilder.Entity<Bar>()
            .HasOptional(f => f.Baz). //Baz is dependent and gets a FK BarId
            .WithRequired(s => s.Bar);//Bar is principal

modelBuilder.Entity<Baz>()
            .HasOptional(f => f.Bar). //Bar is dependent and gets a FK BazId
            .WithRequired(s => s.Baz);//Baz is principal

The dependent gets the foreign key that references the principal's key. When it's a one to one, that foreign key is also the dependent's primary key but EF can't work out which is which and that's why you get an error until you've specified it.

References:

http://msdn.microsoft.com/en-us/library/ee382827.aspx

https://stackoverflow.com/a/19580798/150342

The trick with 1:1 in EF is the dependant table MUST have the same primary key. The Primary tables has the DB generated ID. The dependant uses DatabaseGeneratedOption.None !

so the fluentAPI for the dependant table

 {
  // map for Dependant
  // Relationship
        this.HasKey(t => t.Id);
        // Properties
        //Id is an int allocated by DB but controller via Primary here
        this.Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None); // from parent
        entity.HasRequired(t => t.NAV_PROP_TO_PRIMARY)
              .WithOptional(t => t.NAV_PROP_DEPENDANT) // if it is declared. NOT required.
              .WillCascadeOnDelete(true);   // as appropriate
 }   

 {
     //map for Primary
     // Primary Key
     this.HasKey(t => t.Id);

     // Properties
     //Id is an int allocated by DB
    this.Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); // default to db generated

 }


public class Dependant{ 
   public  virtual int Id { set; get; }
   //... other props
   public virtual Primary Primary {get; set;}   // nav to primary
} 

public class Primary{ 
   public  virtual int Id { set; get; }

} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!