db 中有两个实体,Cars 和 Car's image:
public class Car
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public string Title { get; set; }
}
和
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; }
}
一切都很好,工作正常。示例:car with car is = 123 有 5 张图片,其中一张被标记为“主要”(第一张上传的图片或由主持人手动选择)。
然后我决定优化数据库模型:删除
IsPrimaryImage
并将 PrimaryImage
添加到 Car,如下所示: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 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; }
}
(汽车可能不包含图像 - 这就是为什么
int?
,而不是 int
)编译,运行 -- 失败,错误:
在 stackoverlow 上找到了许多关于此错误的类似主题:
是否可以使用数据注释 修复错误 ? EF 版本是 6。
最佳答案
找到正确的方法:
public class Car
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CarID { get; set; }
[Required]
public string Title { get; set; }
public int? PrimaryImageID { get; set; }
[ForeignKey("CarImageID")]
public virtual CarImage PrimaryImage { get; set; }
}
和
public class CarImage
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CarImageID { get; set; }
[Required]
public int CarID { get; set; }
[ForeignKey("CarID")]
[Required]
public virtual Car Car { get; set; }
public string FileName { get; set; }
}
附言不幸的是,这不适用于此类 ID:
public class Car
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
}
和
public class CarImage
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
}
更新:如果您将您的属性指定为
ID
并将 ForeignKey 指定为 Id
- 这将导致错误:所以,这也有效(区分大小写!):
public class Car
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public string Title { get; set; }
public int? PrimaryImageID { get; set; }
[ForeignKey("ID")]
public virtual CarImage PrimaryImage { get; set; }
}
和:
public class CarImage
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public int CarID { get; set; }
[ForeignKey("ID")]
[Required]
public virtual Car Car { get; set; }
public string FileName { get; set; }
}
关于c# - 先通过数据标注在EF Code中实现一对零或一的关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41640913/