Entity framework EF/CodeFirst关系映射
我有一种情况,我有职业描述和形象。我想建立一对零或多的关系。如果存在JobDescription,它可能有图像集合,也可能根本没有任何图像。Image和ImageSection也是如此。我的课程做得对吗Entity framework EF/CodeFirst关系映射,entity-framework,code-first,Entity Framework,Code First,我有一种情况,我有职业描述和形象。我想建立一对零或多的关系。如果存在JobDescription,它可能有图像集合,也可能根本没有任何图像。Image和ImageSection也是如此。我的课程做得对吗 public class JobDescription { public int JobDescriptionID { get; set; } // Other attributes and navigations
public class JobDescription
{
public int JobDescriptionID { get; set; }
// Other attributes and navigations
public int? ImageID { get; set; }
[ForeignKey("ImageID")]
public virtual List<Image> Image { get; set; }
}
public class Image
{
public int ImageID { get; set; }
public string ImageName { get; set; }
public int? ImageSectionID { get; set; }
[ForeignKey("ImageSectionID")]
public virtual ImageSection ImageSection { get; set; }
}
外键属性属于关系的一方,而不是多方。您的模型类应如下所示:
public class JobDescription
{
public int JobDescriptionID { get; set; }
// Other attributes and navigations
public virtual List<Image> Image { get; set; }
}
public class Image
{
public int ImageID { get; set; }
public string ImageName { get; set; }
public int? JobDescriptionID { get; set; }
[ForeignKey("JobDescriptionID")]
public virtual JobDescription JobDescription { get; set; }
}
对于ImageSection,也是同样的关系。如果图像必须始终具有JobDescription,则图像中的JobDescriptionID必须为int类型,而不是int?。在本例中,ForeignKey属性不是必需的,因为EF将通过命名约定识别FK属性。为什么图像中有ForeignKey?我认为Image的ForeignKey应该在jobscription一侧,因为一个jobscription可能有许多图像,正如您在第一段中所解释的那样。@aneal:在第一段中的单面,我指的是一个引用是Image.jobscription的一侧,而集合是jobscription.Images的一侧。想想如何在关系数据库中建模一对多关系:如果一个JobDescription有多个映像,则映像表必须有一个外键JobDescriptionID to JobDescription。特定JobDescription的所有图像都具有相同的外键值。上面的模型表达了这种数据库关系。