I am trying to bind a tree view menu control in a partialview with the ViewModel. I have created a nested viewModel assuming that is the rightway to carry all the nested data needed for the navigation tree menu at one time and so I have wrote my linq query to fetch the data in a nested fashion. As newbie I am not 100% sure that this is the right way to do it. I am trying to bind my view model with Linq query result. My Model is nested and so is my Linq query. I am facing difficulty molding this two together. What ever way I try I am getting type casting error such as cannot convert from Type IQueriable to IList of collections.. My code:
// ViewModel
namespace My.Namespace
{
public class MyViewModel
{
public decimal CategoryID { get; set; }
public string CategoryName { get; set; }
public decimal Badge { get; set; }
public IList<SubCategories> CategorySubCategories { get; set; }
}
public class SubCategories
{
public decimal SubCategoryID { get; set; }
public string SubCategoryName { get; set; }
public decimal Badge { get; set; }
public List<Items> SubCategoryItems { get; set; }
}
public class Items
{
public decimal ID { get; set; }
public string ItemName { get; set; }
public List<SubItems> SubItems { get; set; }
}
public class SubItems
{
public decimal ID { get; set; }
public string SubItemName { get; set; }
}
}
//Databinding code:
MyViewModel result = new MyViewModel();
var query= (List<MyViewModel>)(from c in dbContext.TableName
where c.CHILD_ID == 0
select new MyViewModel
{
CategoryID = c.ELEMENT_ID,
CategoryName = c.CHILD_DESC,
CategorySubCategories = (List<SubCategories>)(from s in dbContext.TableName
where s.PARENT_ID == c.ELEMENT_ID
select new SubCategories
{
SubCategoryID = s.ELEMENT_ID,
SubCategoryName = s.CHILD_DESC,
SubCategoryItems = (List<Items>)(from i in dbContext.TableName
where i.PARENT_ID == s.ELEMENT_ID
select new Items
{
ID = i.ELEMENT_ID,
ItemName = i.CHILD_DESC
}
)
}
)
});
return query.toList();
The error I am getting is @ line: var query = (List)(from c in dbContext.TableName
Error:
Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery1[MyViewModel]' to type 'System.Collections.Generic.List
1[MyViewModel]'.
On your view model, change your List types to IEnumerable types. Make sure not to use the .ToList() extension method on those sub selects.
The resulting types of your sub select statements are not instances of List, but do implement the IEnumerable interface. They may implement ICollection, IList, etc, but you can play around with that.