如何首先设置一对一关系实体框架代码

时间:2015-03-27 01:22:10

标签: entity-framework

我试图在这里遵循许多类似的问题,但我无法让它发挥作用。我正在从一个变为多个一对一。每个Measurement都有一个ClientPicture。

  

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

 public class ClientPicture
{
   public int Id { get; set; }
    public string ClientPictureUrl { get; set; }
    public string ClientName { get; set; }
    public DateTime? ClientPictureDate { get; set; }

    public Guid MeasurementId { get; set; }
    [ForeignKey("MeasurementId")]
    public virtual Measurement Measurement { get; set; }
}

测量

 public class Measurement
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
    public Guid Id { get; set; }
    public DateTime? MeasurementDate { get; set; }
    public decimal? BustMeasurement { get; set; }
    public decimal? ChestMeasurement { get; set; }
    public decimal? WaistMeasurement { get; set; }
    public decimal? HipsMeasurement { get; set; }

    public int ClientPictureId { get; set; }
    [ForeignKey("ClientPictureId")]
    public virtual ClientPicture ClientPicture { get; set; }
}

1 个答案:

答案 0 :(得分:2)

在一对一关系中,一端必须是 principal ,另一端必须是依赖。应该首先插入主体,并且可以在没有依赖的情况下存在。从属端是必须在主体之后插入的端,因为它具有主体的外键。

我认为你有两种选择:

  • 您在两个实体中使用相同的Id,并且dependend的Id被声明为一对一关系的FK

    //The principal
    public class ClientPicture
    {
      public int Id { get; set; }
      //...
      public virtual Measurement Measurement { get; set; }
    }
    //The dependent
    public class Measurement
    { 
      [Key, ForeignKey("ClientPicture")]
      public int ClientPictureId { get; set; }
      public virtual ClientPicture ClientPicture { get; set; }
    }
    
  • 您在实体中使用不同的ID,但只能使用导航属性:

    public class ClientPicture
    {
      public int Id { get; set; }
      //...
      public virtual Measurement Measurement { get; set; }
    }
    
    public class Measurement
    { 
      [Key]
      [DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
      public Guid Id { get; set; }
      //...
    
      [Required]
      public virtual ClientPicture ClientPicture { get; set; }
    }
    

    EF允许您以一对一的关系映射FK的唯一方法是将FK声明为PK(如第一个变体)。查看此link了解详情