0

我在控制器中有这段代码

Expression<Func<Title, bool>> filterExpr = null;
        Func<IQueryable<Title>, IOrderedQueryable<Title>> orderByFunc = null;           
        List<Title> titles = unitOfWork.TitleRepository.Get(filter: filterExpr, orderBy: orderByFunc, includeProperties: "").ToList();           
        return View("Index", titles);

这是模型

public partial class Title
{
    public Title()
    {
        this.NumberTitles = new HashSet<NumberTitle>();
        this.Title1 = new HashSet<Title>();
    }

    public int Id { get; set; }
    public string TitleText { get; set; }
    public Nullable<int> TitleId { get; set; }

    public virtual ICollection<NumberTitle> NumberTitles { get; set; }
    public virtual ICollection<Title> Title1 { get; set; }
    public virtual Title Title2 { get; set; }
}

这是视图

@model IEnumerable<CinemavaadabiatModel.Title>    
<table>    
@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.TitleText)
    </td>
</tr>
}
</table>

当我运行它时,我收到以下错误

传入字典的模型项的类型为“System.Collections.Generic.List 1[Project.Title]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[Project.Title]”。我的问题在哪里?

4

1 回答 1

0

在将存储库 get 方法的结果返回到视图之前,您将其转换为列表。您可以将视图中模型的类型更改为List<CinemavaadabiatModel.Title>或将控制器操作更改为不调用.ToList()unitOfWork.TitleRepository.Get方法(假设它返回一个IEnumerable):

Expression<Func<Title, bool>> filterExpr = null;
Func<IQueryable<Title>, IOrderedQueryable<Title>> orderByFunc = null;           
var titles = unitOfWork.TitleRepository.Get(filter: filterExpr, 
  orderBy: orderByFunc, includeProperties: "");           
return View("Index", titles);

它看起来好像返回了一个IQueryable虽然,所以你最好将这个IQueryable域模型转换为IEnumerable你可以在视图中使用的视图模型,从而保持域和表示层关注点分开。

更新:

作为替代方案,您可以创建一个TitleViewModel并将标题添加到其中:

public class TitleViewModel
{
    public TitleViewModel()
    {
        this.Titles = new List<CinemavaadabiatModel.Title>();
    }

    public IEnumerable<CinemavaadabiatModel.Title> Titles { get; set; }
}

然后您的控制器代码变为:

Expression<Func<Title, bool>> filterExpr = null;
Func<IQueryable<Title>, IOrderedQueryable<Title>> orderByFunc = null;           
var titles = unitOfWork.TitleRepository.Get(filter: filterExpr, 
  orderBy: orderByFunc, includeProperties: ""); 

// consider using some kind of factory to create your ViewModel 
// if unit testing is a concern
var viewModel = new TitleViewModel { Titles = titles.AsEnumerable() }; 
return View("Index", viewModel);

你的观点变成:

@model TitleViewModel
<table>    
@foreach (var item in Model.Titles) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.TitleText)
    </td>
</tr>
}
</table>
于 2013-10-21T08:14:57.070 回答