There's two entities in db, Cars and Car's image:
public class Car
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public string Title { get; set; }
}
and
public class CarImage
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public int CarID { get; set; }
[ForeignKey("CarID")]
public virtual Car Car { get; set; }
public string FileName { get; set; }
public bool IsPrimaryImage { get; set; }
}
It's all good, works fine. Example: car with car is = 123 has 5 images, one of them has been marked as 'primary' (first uploaded image or manualy choosen by moderator).
Then i decide to optimize db model: remove IsPrimaryImage
and add PrimaryImage
to Car as shown here:
public class CarImage
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public int CarID { get; set; }
[ForeignKey("CarID")]
public virtual Car Car { get; set; }
public string FileName { get; set; }
}
and
public class Car
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public string Title { get; set; }
public int? PrimaryImageID { get; set; }
public virtual CarImage PrimaryImage { get; set; }
}
(Car may contain no images - that's why int?
, not int
)
Compile, run -- failed with error:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Unable to determine the principal end of an association between the types 'MyApp.Domain.CarImage' and 'MyApp.Domain.Car'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
Found many similar topics on stackoverlow about this error:
- first, commons
- second, same error but 1:1 relationship, not my case
- third, looks like my case because about 1:0..1 but fluent API only.
Is it possible to fix error with data annotation? EF version is 6.