Reputation: 6387
I am trying to follow many of the similar questions on here but I cannot get it working. I am changing from a one to many to a one to one. Every Measurement will have one ClientPicture.
Unable to determine the principal end of an association between the types 'FitFactor.Models.Clients.ClientPicture' and 'FitFactor.Models.Clients.Measurement'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
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; }
}
Measurement
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; }
}
Upvotes: 1
Views: 31
Reputation: 39326
In an one-to-one relation one end must be principal and the other end must be the dependent. The principal should be inserted first and can exist without the dependent. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.
I think you have two options here:
You use the same Id in both entities and the Id of the dependend is declared as the FK of the one to one relationship
//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; }
}
You use different Ids in your entities but you can work only with the navigation properties:
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; }
}
The only way that EF lets you map the FK in an one-to-one relationship is when the FK is declared as a PK too (like the first variant). Check this link for more info
Upvotes: 2