My Linq2Sql statements gaves me what I what I required. Below is my method returning anonymous list of category and all its related subcategories:
public IQueryable GetAllCategoriesAndSubcategories()
{
return from p in _context.Categories
let relatedchilds = from c in _context.SubCategories
where c.CategoryId == p.Id
select c
select new
{
p,
relatedchilds
};
}
In my code behind i am using this method to fetch category and all its subcategory:
private void WriteCategories()
{
var repository = new CategoryRepository();
var dt = repository.GetAllCategoriesAndSubcategories();
var sb = new StringBuilder();
sb.AppendLine(" <div class='widget_box' id='category'>");
sb.AppendLine(" <div class='wintitle'>");
sb.AppendLine(" <div class='inner_wintitle'>Categories</div>");
sb.AppendLine(" </div>");
sb.AppendLine(" <div class='winbody'>");
sb.AppendLine(" <ul class='categories'>");
int i = 1;
foreach (Category category in dt.OfType<Category>())
{
sb.AppendLine(
string.Format("<li class='catetitle' id='catetitle{0}'><a href='/category/{1}/{2}'>{3}</a></li>", i,
category.Id, Common.ReplaceUnwantedChars(category.Name), category.Name));
sb.AppendLine("<li style='display:none;' class='category_sub' ><div><ul>");
foreach (var subCategory in dt.OfType<SubCategory>())
{
sb.AppendLine(string.Format("<li><a href='category/{0}/{1}/{2}'>{3}</a></li>", category.Id,
subCategory.Id, Common.ReplaceUnwantedChars(subCategory.Name),
subCategory.Name));
}
i++;
}
sb.AppendLine("</div></ul></div>");
ltlCategories.Text = sb.ToString();
}
Adding watch I got the stuff give below:
[0] { p = {InnovativeTechnosoft.BusinessBazaar.Web.UI.Core.Category}, relatedchilds = {System.Collections.Generic.List`1[InnovativeTechnosoft.BusinessBazaar.Web.UI.Core.SubCategory]} } <Anonymous Type>
Requirement : From code itself its clear that I need to iterate through the category and its subcategory. I am trouble and condition check where I am using dt.OfType<Category>(). If I use simply foreach(Category c in dt), it gives me casting exception.
Please help. Where and what I am doing wrong.
What your method
GetAllCategoriesAndSubcategories()returns is anIQueryableof an anonymous type – instances of this type are not Category objects so the cast will always fail, andOfType<Category>()will simply return an empty collection.Instead projecting to an anonymous type use a helper class that will allow you to use it later on, i.e.:
Then change the method signature of
GetAllCategoriesAndSubcategoriesto:Now you can query the returned enumeration like: