我无法理解如何在我正在构建的项目中创建类之间的关系。
我的班级Photo
与PhotoExif
具有必需的一对一关系,而Photo
与FeaturedPhoto
具有可选的一对一关系
我收到了错误:
无法确定类型
Website.Models.PhotoExif
的复合主键排序。使用ColumnAttribute
或HasKey
方法指定复合主键的顺序。
非常感谢帮助。
Photo.cs
public class Photo
{
[Key]
public int PhotoID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public Orientation Orientation { get; set; }
public int Rating { get; set; }
public string URL { get; set; }
public string Filename { get; set; }
public DateTime DateAdded { get; set; }
public bool Hide { get; set; }
public string MetaDescription { get; set; }
public string MetaKeywords { get; set; }
public virtual PhotoExif PhotoExif { get; set; }
}
PhotoExif.cs
public class PhotoExif
{
[Key]
public int PhotoExifID { get; set; }
public int PhotoID { get; set; }
public string ShutterSpeed { get; set; }
public string Aperture { get; set; }
public string FocalLength { get; set; }
public int ISO { get; set; }
public string ExposureBias { get; set; }
public bool Flash { get; set; }
public string WhiteBalance { get; set; }
public string Lens { get; set; }
public DateTime DateTaken { get; set; }
public float Longitude { get; set; }
public float Latitude { get; set; }
public int Zoom { get; set; }
public string Location { get; set; }
public virtual Photo Photo { get; set; }
}
FeaturedPhoto.cs
public class FeaturedPhoto
{
[Key]
public int FeaturedPhotoID { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string InformationLocation { get; set; }
public string ImagePosition { get; set; }
public virtual Photo Photo { get; set; }
}
答案 0 :(得分:1)
根据错误消息:
使用ColumnAttribute或HasKey方法指定订单 复合主键。
您需要将[Column(Order =“#”)]注释添加到PhotoExif表的PhotoID和PhotoExifID属性。
答案 1 :(得分:0)
对我而言,您认为PhotoExif
上不需要复合主键。我不知道为什么EF会尝试推断复合键,但原因可能是1)Photo
属性按惯例将PhotoID
属性作为外键,2)在一对一中 - 一个关系外键必须与主键相同,3)还有另一个属性PhotoExifID
,您已标记了一个键。因此,也许,EF假设这个标记的密钥加上一对一关系中的被动密钥形成一个复合密钥。 (这种行为很奇怪,但我看不出你的模型和注释如何导致关于复合键排序的这种异常。)
无论如何,PhotoID
属性似乎不对,因为在一对一关系中,principal和dependent必须共享相同的主键,并且依赖项的FK同时是PK。我会尝试删除此属性并添加FK属性:
public class PhotoExif
{
[Key]
public int PhotoExifID { get; set; }
public string ShutterSpeed { get; set; }
//...
[ForeignKey("PhotoExifID")]
public virtual Photo Photo { get; set; }
}
同样,你必须为FeaturedPhoto
定义FK,否则EF无法确定什么是主体以及关系的依赖性。根据关系的详细信息 - 它们是必需的 - 必需的 - 必需的 - 可选的还是可选的 - 可选的,哪个实体是主体,哪个是依赖的? - 可能需要使用Fluent API定义映射,因为数据注释不支持Fluent API所做的每个映射选项。