C# ASP.NET MVC3和实体框架-一个视图中的一对多关系

C# ASP.NET MVC3和实体框架-一个视图中的一对多关系,c#,entity-framework,C#,Entity Framework,我正在学习MVC3,我有一个问题 我的模型中有两张桌子(图库和图像)。这些表格由GalleryId(1个图库-多个图像)关联(一对多) 在Gallery->Details视图中,我想插入Gallery详细信息(很简单)和一件事-来自此Gallery的图像列表。我不知道怎么做。 以下是此模型中的类: public partial class Gallery { public Gallery() { this.Images = new HashSet<Image

我正在学习MVC3,我有一个问题

我的模型中有两张桌子(图库和图像)。这些表格由GalleryId(1个图库-多个图像)关联(一对多)

在Gallery->Details视图中,我想插入Gallery详细信息(很简单)和一件事-来自此Gallery的图像列表。我不知道怎么做。 以下是此模型中的类:

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; }
}
公共部分类库
{
公众席()
{
this.Images=newhashset();
}
公共int Id{get;set;}
公共字符串名称{get;set;}
公共字符串密码{get;set;}
public System.DateTime CreatedOn{get;set;}
公共虚拟ICollection映像{get;set;}
}
公共部分类映像
{
公共int Id{get;set;}
公共字符串名称{get;set;}
公共字符串文件名{get;set;}
public int GalleryId{get;set;}
public System.DateTime上载到{get;set;}
公共虚拟库库{get;set;}
}
公共部分类MyEntities:DbContext
{
公共数据库集库{get;set;}
公共数据库集映像{get;set;}
}

最好的方法是什么?

在detailview中,您使用Gallery作为模型(在控制器中,您返回所需的Gallery
返回操作结果视图(service.GetGallery(id));

在视图中有一个循环:

@foreach (var item in Model.Images.Select((model, index) => new { index, model }))
{
    <div>@(item.index). @item.model.Name </div>
}
@foreach(Model.Images.Select((Model,index)=>new{index,Model})中的变量项)
{
@(item.index)。@item.model.Name
}

最简单的方法是在要传递到详细信息视图的模型中传递它

public ActionResult Details(int id)
{
     var item = //get gallery item from database

     item.ImagesReference.Load();

     return View(item);
}
在您看来,您可以执行以下操作:

<ul>
    <%: if (Model.Images != null) foreach(var item in Model.Images) { %>
         <li> <%: item.Name %> </li> 
    <% } %>
</ul>
您也可以通过ViewData传递列表,但我认为在您的模型中传递它会更整洁,因为它不需要设置任何其他变量,EF会在模型中为您这样做


注意:我输入的一些名称可能已关闭,但Intellisense将为您提供正确的名称,因为EF已经生成了这些对象。我希望您理解我试图解释的基本思想:-)

这更多是一个关于实体框架的问题,而不是MVCLooks更像NHibernate。。。。当您想在视图中显示图像时,是否可以不执行foreach循环,因为图像是Gallery的属性?foreach(画廊中的var image.Images)并以这种方式循环浏览图像?