Linq 显示ID下的内容

Linq 显示ID下的内容,linq,entity-framework-4,asp.net-mvc-4,ef-code-first,foreign-keys,Linq,Entity Framework 4,Asp.net Mvc 4,Ef Code First,Foreign Keys,我已经学习EF和LINQ很长一段时间了,我很难在我试图完成的以下过程中收集答案: 在索引视图中,我希望有一个所有CD及其各自内容的列表。有关更多信息,请参见以下课程: public class Cd { public int cdID { get; set; } public string cdName { get; set; } public string tag { get; set; } public Content

我已经学习EF和LINQ很长一段时间了,我很难在我试图完成的以下过程中收集答案:

在索引视图中,我希望有一个所有CD及其各自内容的列表。有关更多信息,请参见以下课程:

 public class Cd
    {
        public int cdID { get; set; }
        public string cdName { get; set; }
        public string tag { get; set; }
        public Content Content { get; set; }
    }

    public class Content
    {

        public int contentID { get; set; }
        public string contentName { get; set; }
        public string category { get; set; }
    }
给定这些类,我如何实现我要做的事情—使用cdID在CD下显示所有CD内容

更新1-感谢DryadWoods的最终答案

public class Cd
{
    public int cdID { get; set; }
    public string cdName { get; set; }
    public string tag { get; set; }
    public IList<Content> Content { get; set; }  //Changes here! No changes in Content class
}
视图的最终版本:

@model IEnumerable<MediaManager.Models.Cd>

<table>
    <tr>
        <th>CD ID</th>
        <th>Content</th>
    </tr>

    @foreach (var cd in Model) //nested loop for displaying the cdID, then proceeds to loop on all contents under certain cdID
    {
        <tr>

            <td>
                @Html.DisplayFor(modelItem => cd.cdID)
            </td>
            <td>
            @foreach (var item in cd.Content)
            {
                <p>@item.contentName</p>
            }
            </td>
        </tr>
    }

</table>

举个简单的例子,在一个页面上显示所有CD和每个CD的内容

控制器:

    public ViewResult Index(){
           return View(db.Cd.Include(x=>x.Content).ToList());
    }
视图:

    @model IEnumerable<YourNamespace.Cd>

    @foreach (var cd in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => user.UserName)
                   .... etc ...
        </td>    
        <td>
            @foreach (var c in cd.Content ) {
              <div>
                   @c.contentName 
                   .... etc ...
              </div>
            }
        </td>            
    </tr>
     }
更新1

将类更改为:

 public class Cd
    {
        public int cdID { get; set; }
        public string cdName { get; set; }
        public string tag { get; set; }
        public IList<Content> Contents { get; set; }
    }

现在你有了一个内容列表:

你是说一张Cd有很多内容对象,对吗?那么内容不应该是数组吗?我同意,我最终将内容的数据类型更改为public-IList-Content{get;set;}..谢谢您的快速回答。。简单想一想,我不应该使用任何ICollection数据类型吗?对于这种情况,没有问题,有关更多信息,请查看此问题:我尝试了您建议的解决方案,但它不起作用。而且我尝试了以下建议:其中我修改了我的类,使其具有对content类的虚拟Icollection引用,但收到以下错误:CS1061:“System.Collections.Generic.IEnumerable”不包含“content”的定义,并且没有接受第一个类型参数的扩展方法“content”可以找到“System.Collections.Generic.IEnumerable”您可以编写您遇到的异常吗?上面,我发布了异常。以下是视图的逻辑:CD ID Content@foreach var-CD in Model.Content{@Html.DisplayFormodelItem=>CD.C}