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

asp.net-mvc, asp.net-mvc-4, c#

Solution

The `db.TourCategories()` method does not return a collection of `TourCategoryList`, so you'll have to do a little more work to convert whatever class `TourCategories()` returns into a `TourCategoryList`, using the LINQ `Select()` method.

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

I'm assuming that `TourCategories()` returns a collection of `TourCategory`.

If I could make one other suggestion, you might want to rename `TourCategoryList`. I know you're trying to differentiate it from the other `TourCategory` class, but someone looking at your code might assume (at first glance) that `List<TourCategoryList>` is a list of lists, just from the name.

Problem

I want to populate a viewmodel with a DateTime property, and also a list of categories. 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; } } ``` Domain model: ``` public class TourCategory { public int TourCategoryId { get; set; } public string TourType { get; set; } public virtual ICollection<Tour> Tour { get; set; } } ``` I thought I could populate it easily with this code: ``` var viewModel = new TourCategoryVM(); viewModel.TourCategoryList = db.TourCategories(); ``` However, I'm getting the error: Error 1 Cannot implicitly convert type `System.Data.Entity.DbSet<tb.Models.TourCategory>` to `System.Collections.Generic.List<tb.Models.ViewModels.TourCategoryList>` Is it my ViewModel that's wrong?

Original source