EF /代码优先关系映射

时间:2012-06-23 10:37:41

标签: entity-framework code-first

我的情况是我有班级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; }


        }

1 个答案:

答案 0 :(得分: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的关系相同。如果始终的图片必须<{1}},则JobDescription中的JobDescriptionID必须是Image类型,而不是int。在此示例中,int?属性不是必需的,因为EF将通过命名约定来识别FK属性。