Retrieve data from three foreign key relationship tables in one View – Index() action

<div>

[Table("Album")]
    public class Album
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int albumid { get; set; }
        public string albumname { get; set; }

        public virtual ICollection<Photo> Photos { get; set; }
    }

[Table("Photo")]
    public class Photo
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int photoid { get; set; }
        public string photoname { get; set; }
        public int albumid { get; set; }   
        
        public virtual Album Album { get; set; }
        public virtual ICollection<Tag> Tags { get; set; }       
    }

[Table("Tag")]
    public class Tag
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int tagid { get; set; }
        public string tagname { get; set; }
        public int photoid { get; set; }

        public virtual Photo Photo { get; set; }
    }

This is my model class:

    public class MyPhotoModel
    {

              ????

    }

    public ActionResult Index()
    {           
          var model = ????
          return View(model);
    }

</div>

Hi hmsarab,

To include the child entity, we could use Include method.

For your requirement, you could retrieve the data directly and return to the view.

public ActionResult Index()
     {            
           //TODO instance database context
           var model = db.Album.Include(a=>a.Photos.Select(p=>p.Tags)).ToList();
           return View(model);
     }
<div>
 @Model[0].Photos[0].Tags[0].tagname
<div>

Best Regards

Starain

I tested view page code but it does not correct and does not work. I got an error.

thanks

Leave a Reply