0

我在两个表上有这个 LINQ 查询

public ViewResult data()
        {
            var query = from a in DB.Album
                        join b in DB.Artists
                        on a.ArtistId equals b.ArtistId
                        where (b.ArtistId == 2)
                       select new { a ,b };

            return View(query.ToList());
        }

但是我很困惑如何在我的视图中显示这些数据,即艺术家表的艺术家姓名和专辑表专辑名称?

我正在尝试这样的事情,但它给了我一个错误

@model IEnumerable<test1.Models.Album>


@{
    ViewBag.Title = "data";
}

<h2>data</h2>

@Model.Count()
<br />
<ul>
@foreach (var mod1 in Model)
{
    <li>

   @* @mod1.Genre.Name*@
      @Html.DisplayFor(modelItem => mod1.Artist.Name)
    <br />
    @mod1.AlbumId
   <br />
    @mod1.Artist
    <br />
    @mod1.Title
    </li>
}
</ul>

我得到的错误是

传入字典的模型项的类型为“System.Collections.Generic.List 1[<>f__AnonymousType1 2[test1.Models.Album,test1.Models.Artist]]”,但此字典需要类型为“System.Collections.Generic”的模型项.IEnumerable`1[test1.Models.Album]'。

任何想法 ?

4

2 回答 2

0

创建一个新的视图模型来存储所有需要的信息

将您的操作更改为返回该 ViewModel

更改视图以获取新视图模型类型的模型,并根据需要获取属性。

于 2012-09-06T10:30:17.390 回答
0

You are getting the exception because you are trying to pass a list of anonymous objects instead of a list of albums.

You can create a viewmodel so you can use that type as your model.

public class ArtistAlbumViewModel
{
    Artist Artist { get; set; }
    Album Album { get; set; }
}

Use this type when you return values from the query.

var query = from a in DB.Album
            join b in DB.Artists
            on a.ArtistId equals b.ArtistId
            where (b.ArtistId == 2)
            select new ArtistAlbumViewModel { Album = a, Artist = b };

Then you should strongly type your view to this type and edit the view according to your viewmodel.

@model IEnumerable<test1.Models.ArtistAlbumViewModel>
于 2012-09-06T10:29:03.780 回答