How to show all data from three relationship forignkey tables in index action with my model

I have created 3 tables by Code first approach using EF MVC 4

  • between Album table and Photo table I have one to many relationship
  • between Photo table and Tag table I have one to many relationship

These are my tables:

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

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

This is my model class:

public class MyPhotoModel
    {
        public IEnumerable<Photo> Photos { get; set; }
        public IEnumerable<Album> Album { get; set; }
        public ICollection<Tag> Tags { get; set; }

}

How can I read all three tables data in a table inside Index()  in controller page and show them in View page???

  MyPhotoModel model = new MyPhotoModel();
            model.Photos = db.Photos.Include("Album")
                                                   .Include("Tags");   

return View(model);

Hi hmsarab,

Thanks for your post.

hmsarab

How to show all data from three relationship forignkey tables in index action with my model

Please check Mike’s article:

#ASP.NET MVC, Entity Framework, One-to-Many and Many-to-Many INSERTS

http://www.mikesdotnetting.com/Article/109/ASP.NET-MVC-Entity-Framework-One-to-Many-and-Many-to-Many-INSERTS

Hope this can be helpful.

Best Regards,

Eileen

It is not my answer, I told that I need to read all tree tables data in a index() action

Just I need a single line as piece of code

Thanks

good post

Leave a Reply