给出以下数据库结构
类别
ID
CategoryNameResID
ParentCategory(可选)
资源
ID
文本
郎
并给出了一个ViewModel
public class CategoryViewModel { public int ID { get; set; } public int CategoryNameResID { get; set; } public string CategoryName { get; set; } public int ParentCategory { get; set; } public string ParentCategoryName { get; set; } }
我想获得包含ParentCategoryName的所有类别的列表
到目前为止我所做的是:
var categories = (from cat in db.Categories join res in db.Resources on cat.CategoryNameResID equal res.ID select new CategoryViewModel{ ID = cat.ID,CategoryNameResID = cat.CategoryNameResID,CategoryName = res.Text,ParentCategory = cat.ParentCategory,ParentCategoryName = (from p in db.Resources where p.ID == cat.ParentCategory select p.Text) }).ToList();
我无法弄清楚如何获取ParentCategoryName而不必再次迭代,这绝对是错误的.
解决方法
试试这个:
(from cat in cats join res in resources on cat.ResId equals res.Id let categoryName = res.Text join cat1 in cats on cat.ParentId equals cat1.Id into parentJoin from pj in parentJoin.DefaultIfEmpty() let parentCatResId =pj==null?0: pj.ResId join res1 in resources on parentCatResId equals res1.Id into resJoin from res2 in resJoin.DefaultIfEmpty() let parentName = (res2==null?string.Empty:res2.Text) select new CategoryVM { Id = cat.Id,ResId = cat.ResId,CatName = categoryName,ParentId = cat.ParentId,ParentName = parentName }).ToList();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。