Mar*_*ark 5 c# asp.net-mvc asp.net-mvc-4
我想用一个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();
但是,我收到错误:
错误1无法将类型隐式转换
System.Data.Entity.DbSet<tb.Models.TourCategory>为
System.Collections.Generic.List<tb.Models.ViewModels.TourCategoryList>
这是我的ViewModel错了吗?
该db.TourCategories()方法不返回一个集合TourCategoryList,因此您将不得不做一些工作,使用LINQ 方法将任何类TourCategories()返回转换为a .TourCategoryListSelect()
viewModel.TourCategoryList = db.TourCategories()
                               .Select(tc => new TourCategoryList
                                             {
                                                 TourCategoryId = tc.TourCategoryId,
                                                 TourType = tc.TourType
                                             })
                               .ToList();
我假设它TourCategories()返回一个集合TourCategory.
如果我可以提出另一个建议,您可能需要重命名TourCategoryList.我知道你正试图将它与其他TourCategory类区分开来,但是看着你的代码的人可能会(从第一眼看出)假设这List<TourCategoryList>是一个列表列表,仅从名称开始.