My News.cs类与Comment.cs有一对多的关系,如下所述
public class News
{
public int NewsId { get; set; }
[Display(Name = "Title")]
public string Title { get; set; }
[Display(Name = "Details")]
public string Details { get; set; }
public DateTime DateCreated { get; set; }
public int AppUserId { get; set; }
[ForeignKey("AppUserId")]
public virtual AppUser AppUser { get; set; }
public ICollection<Comment> Comment { get; set; }
}
public class Comment
{
public int CommentId { get; set; }
public string CommentText { get; set; }
public DateTime DateCreated { get; set; }
public int AppUserId { get; set; }
public int? NewsId { get; set; }
[ForeignKey("AppUserId")]
public virtual AppUser AppUser { get; set; }
[ForeignKey("NewsId")]
public virtual News News { get; set; }
}
我有一个控制器动作,我试图获取一个新闻项目及其所有评论,所以我设置了两个像这样的viewModels
public class CommentVM
{
public string CommentText { get; set; }
public DateTime DateCreated { get; set; }
public string Author { get; set; }
}
public class NewsCommentsVM
{
[Display(Name = "Title")]
public string Title { get; set; }
[Display(Name = "Details")]
public string Details { get; set; }
public DateTime DateCreated { get; set; }
public string Author { get; set; }
public List<CommentVM> Comments { get; set; }
}
在我的控制器操作中,我有
public ActionResult Details(int? id)
{
UOW _unit = new UOW();
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
News news = _unit.NewsRepository.GetByID(id);
if (news == null)
{
return HttpNotFound();
}
var model = new NewsCommentsVM()
{
Title = news.Title,
Details = news.Details,
DateCreated = news.DateCreated,
Author = news.AppUser.FirstName
Comments = news.Comment.Select(c => new CommentVM()
{
CommentText = c.CommentText,
Author = c.AppUser.Email,
DateCreated = c.DateCreated
}).ToList()
};
return View(result);
}
问题是调试器显示Comment返回Null,而在数据库中有对该特定新闻项的相关注释,因此我收到错误
值不能为空。参数:source
我已经能够在没有问题的情况下在另一个项目中使用此代码。
答案 0 :(得分:2)
我认为问题是因为您需要将Comments
集合属性更改为virtual
。如果您希望延迟加载相关实体,则需要遵循此requirements:
public class News
{
//...
public virtual ICollection<Comment> Comment { get; set; }
}
现在,如果您已停用lazy loading,则当您需要查找特定新闻时,其他选项可能会在您的查询中使用Include
扩展名方法:
int id=3;
var specificNews=context.News.Include(n=>n.Comment).FirstOrDefault(n=>n.Id==id);
这样,相关实体将包含在查询结果中