无法将类型隐式转换为 'System.Collections.Generic.List

Cannot implicitly convert type to 'System.Collections.Generic.List

我想用 DateTime 属性 和类别列表填充视图模型。

ViewModel:

public class TourCategoryVM
{
    public DateTime Date { get; set; }
    public List<TourCategoryList> TourCategoryList { get; set; }
}

public class TourCategoryList
{
    public int TourCategoryId { get; set; }
    public string TourType { get; set; }
}

领域模型:

public class TourCategory
{
    public int TourCategoryId { get; set; }
    public string TourType { get; set; }
    public virtual ICollection<Tour> Tour { get; set; }
}

我想我可以用这段代码轻松地填充它:

        var viewModel = new TourCategoryVM();
        viewModel.TourCategoryList = db.TourCategories();

但是,我遇到了错误:

Error 1 Cannot implicitly convert type
System.Data.Entity.DbSet<tb.Models.TourCategory> to
System.Collections.Generic.List<tb.Models.ViewModels.TourCategoryList>

是我的 ViewModel 出错了吗?

db.TourCategories() 方法不是 return TourCategoryList 的集合,所以你必须做更多的工作来转换 class [=13] =] returns 转换为 TourCategoryList,使用 LINQ Select() 方法。

viewModel.TourCategoryList = db.TourCategories()
                               .Select(tc => new TourCategoryList
                                             {
                                                 TourCategoryId = tc.TourCategoryId,
                                                 TourType = tc.TourType
                                             })
                               .ToList();

我假设 TourCategories() return 是 TourCategory.

的集合

如果我能提出其他建议,您可能想要重命名 TourCategoryList。我知道您正试图将它与其他 TourCategory class 区分开来,但是查看您的代码的人可能会假设(乍一看)List<TourCategoryList> 是列表的列表,只是来自名字。