我有以下课程:public class Blog { public int Id {get; set;} public String Name {get; set;} ... ... public int CatId {get;set;}}public class BlogCategory{ public int Id {get; set;} public String Name {get; set;} public virtual Blogs {get; set;}}现在我的剃须刀页面中有视图模型:public BlogViewModel{ public int Id {get; set;} public string Name {get; set;} .. .. public string CategoryName {get; set;}}我正在尝试选择博客并包含它的类别名称:我的查询:Blogs = await _context.Blogs .Select(b => new BlogViewModel() { Id = b.Id, Name = b.Name, //CategoryName = }) .ToListAsync();如何根据我拥有的 CatId 从 BlogCategory 表中选择类别名称?一种方法是添加public virtual Category BlogCat {get; set;}到 Blog 类,然后使用 Include 但我不想使用此方法,因为我只想要类别名称而不是完整对象。请问有什么帮助吗?解决方案:Blogs = await _context.Blogs .Select(b => new BlogViewModel() { Id = b.Id, Name = b.Name, CategoryName = _context.BlogCategory .Where(c => c.Id == b.CatId) .Select(c => c.Name) .SingleOrDefault() }) .ToListAsync();
2 回答
心有法竹
TA贡献1866条经验 获得超5个赞
解决方案:
Blogs = await _context.Blogs
.Select(b => new BlogViewModel()
{
Id = b.Id,
Name = b.Name,
CategoryName = _context.BlogCategory
.Where(c => c.Id == b.CatId)
.Select(c => c.Name)
.SingleOrDefault()
})
.ToListAsync();
达令说
TA贡献1821条经验 获得超6个赞
var blogModels = ( from b in _context.Blogs
join c in _context.BlogCategories
on b.CatId equals c.Id
select new BlogViewModel()
{
Id = b.Id,
Name = b.Name,
CategoryName = c.Name
}).ToList();
- 2 回答
- 0 关注
- 110 浏览
添加回答
举报
0/150
提交
取消