无法从'System.Collections.Generic.IList<>'转换至 ''

时间:2013-09-25 02:26:17

标签: c# asp.net-mvc-4

[NonAction]
protected void PrepareNewsCommentModel(NewsCommentModel model, NewsComment newsComment)
{
  if (newsComment == null) throw new ArgumentNullException("newsComment");
  if (model       == null) throw new ArgumentNullException("model");

  model.Id = newsComment.Id;
  model.CommentTitle = newsComment.CommentTitle;
  model.CustomerName = newsComment.CustomerName;
  model.CommentText = newsComment.CommentText;

}

public ActionResult Comments(int number)
{
  if (!_newsSettings.Enabled)
    return RedirectToRoute("HomePage");

  var newsComment = _newsService.GetNewsComment(number);
  var model = new NewsCommentModel();
  PrepareNewsCommentModel(model,newsComment);

  return View(model);
}

这是我的错误:

Error 2 Argument 2: cannot convert from
'System.Collections.Generic.IList<Yapi.Core.Domain.News.NewsComment>' to
'Yapi.Core.Domain.News.NewsComment'
D:\YAPI\Projects\ASCS-Portal\Yapi.Web\Controllers\NewsController.cs 420
40
Yapi.Web

1 个答案:

答案 0 :(得分:2)

错误告诉您问题。 newsCommentIList<NewsComment>,但您的PrepareNewsCommentModel方法需要NewsComment

尝试使用Linq的First扩展方法:

var newsComment = _newsService.GetNewsComment(number).First();

FirstOrDefault如果您的GetNewsComment方法可能返回空列表:

var newsComment = _newsService.GetNewsComment(number).FirstOrDefault();
相关问题