首次使用后,对象属性变为null

时间:2013-08-25 19:19:19

标签: asp.net-mvc

我的控制器中有一些代码如下:

var db = new ComicEntities();
            var user = db.Users.Where(i => i.UserName == username).Include(i => i.UserFavorites);
            var AuthorComics = db.ComicAuthors.Where(i => i.User_Id == 1)
                         .Include(i => i.Comic)
                         .Include("Comic.Chapters")
                         .Include("Comic.Chapters.Pages");
            var Comics = AuthorComics.Select(i => i.Comic).Include("Chapters").Include("Chapters.Pages");
            return View(new LocalUserViewModel { User = user.First(), Comics = Comics.ToList() });

我的观点如下:

@model Comics.Models.LocalUserViewModel

@foreach(var favorite in @Model.User.UserFavorites)
            {
                <div class="chapter-info">
                    <span class="chapter-info-title misc-comic-title">@favorite.Comic.Title</span>
                    <span class="chapter-info-page misc-comic-info">@favorite.DateFavorited</span>
                </div>
            }

问题是在foreach循环的第一次迭代之后,属性@favorite.Comic变为空。

1 个答案:

答案 0 :(得分:1)

现在,您的控制器会查找用户并急切地获取收藏夹,但不会提取下一级别。您需要稍微修改一下您的查询,即

var user = db.Users.Where(i => i.UserName == username)
                            .Include(i => i.UserFavorites)
                            .Include("UserFavorites.Comic");

请注意,其他查询会获取信息,但它们位于不同的对象图上....