ASP.NET MVC3 and Entity Framework - One-to-Many Relationships in One View

I am learning MVC 3 and I am having a problem with something.

I have two tables in my model (Gallery and image). These tables are linked (one-to-many) using GalleryId (1 gallery - many images).

In the gallery β†’ Detailed view, which I would like to insert in the gallery details (which is simple) and another one is a list of images from this gallery. I have no idea how to do this. Here are the classes from this model:

public partial class Gallery { public Gallery() { this.Images = new HashSet<Image>(); } public int Id { get; set; } public string Name { get; set; } public string Password { get; set; } public System.DateTime CreatedOn { get; set; } public virtual ICollection<Image> Images { get; set; } } public partial class Image { public int Id { get; set; } public string Name { get; set; } public string FileName { get; set; } public int GalleryId { get; set; } public System.DateTime UploadedOn { get; set; } public virtual Gallery Gallery { get; set; } } public partial class MyEntities : DbContext { public DbSet<Gallery> Galleries { get; set; } public DbSet<Image> Images { get; set; } } 

What is the best way to do this?

+4
source share
2 answers

In the detailed view, you use the Gallery as a model (in the controller, you return the desired gallery return ActionResult View(service.GetGallery(id));

and in the view you have a loop:

 @foreach (var item in Model.Images.Select((model, index) => new { index, model })) { <div>@(item.index). @item.model.Name </div> } 
+2
source

The easiest way is to pass it to the Model that you pass to the Details view.

 public ActionResult Details(int id) { var item = //get gallery item from database item.ImagesReference.Load(); return View(item); } 

in your opinion, you can do something like:

 <ul> <%: if (Model.Images != null) foreach(var item in Model.Images) { %> <li> <%: item.Name %> </li> <% } %> </ul> 

You can also just pass the list through ViewData, but I think that passing it in your model is more accurate, since it does not require setting any other variable, EF does this for you in the model.

Note. Some of the names I entered may be disabled, but Intellisense will provide you with the correct names, since EF has already generated these objects. Hope you understand the basic idea that I am trying to explain :-)

+1
source

Source: https://habr.com/ru/post/1391255/