[英]Select column from another table based on Id using Entity Framework
我有以下课程:
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,但我不想使用此方法,因为我只希望Category Name(名称)而不是完整对象。
请帮忙吗?
解决方案:
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();
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();
解决方案:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.