0

我有一种情况,我有课JobDescriptionImage. 我想建立一到零或多的关系。如果 JobDescription 存在,它可能有图像集合或根本没有任何图像。Image 和 ImageSection 也是如此。我的课程做得对吗?

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; }


        }
4

1 回答 1

0

外键属性属于关系的“一”方,而不是“多”方。您的模型类应如下所示:

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。如果一个图像总是必须有一个JobDescriptioninJobDescriptionID必须Image是 type int,not int?。在此示例中,该ForeignKey属性不是必需的,因为 EF 将通过命名约定识别 FK 属性。

于 2012-06-23T11:35:15.337 回答