I have a situation where i have classes JobDescription and Image . I want to establish the relation of one to zero or many. If JobDescription exists it may have collection of images or may not have any image at all. Same goes with Image and ImageSection. With my classes am i doing right?
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; }
}
The foreign key property belongs to the “one” side of the relationship, not to the “many” side. Your model classes should look like this:
And the same kind of relationship for
ImageSection. If an image always must have aJobDescriptiontheJobDescriptionIDinImagemust be of typeint, notint?. In this example theForeignKeyattribute is not necessary because EF will recognize the FK property by naming conventions.