无法确定关联的主要结束

时间:2013-11-17 19:19:57

标签: c# entity-framework foreign-keys

首先使用EF5代码,我有两个类:

[Table("UserProfile")]
public class UserProfile {

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTime DateOfBirth { get; set; }

    [ForeignKey("AddressId")]
    public virtual Address Address { get; set; }

}

[Table("Address")]
public class Address : IEntity {

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int AddressId { get; set; }

    public string Address1 { get; set; }

    public string Address2 { get; set; }

    public string City { get; set; }

    public virtual State State { get; set; }

    public string ZipCode { get; set; }

    [ForeignKey("UserId")]
    public virtual UserProfile User { get; set; }
}

UserProfile应始终拥有Address,但我还想在Address中设置导航属性,以便我可以按地址查找用户。因此,一旦迁移完成了它,我希望表格看起来像......

UserProfile
    UserId (PK)
    ...

Address
    AddressId (PK)
    ...
    UserId (FK)

在程序包管理器控制台中,我正在运行update-database并收到以下消息...

  

无法确定类型'TastySerpent.Domain.Models.Address'和'TastySerpent.Domain.Models.UserProfile'之间关联的主要结尾。必须使用关系流畅API或数据注释显式配置此关联的主要结尾。

我对如何在Entity Framework 5中建立一对一关系感到困惑。

2 个答案:

答案 0 :(得分:1)

在映射时定义主体:

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

依赖项获取引用主体密钥的外键。如果它是一对一的,那个外键也是依赖的主键,但是EF无法解决哪个是哪个,这就是为什么在你指定错误之前就会出现错误的原因。

参考文献:

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

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

答案 1 :(得分:0)

EF中1:1的技巧是依赖表必须具有相同的主键。 主表具有DB生成的ID。依赖项使用DatabaseGeneratedOption.None!

所以依赖表的fluentAPI

 {
  // 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; }

}