使用实体框架基于ID从另一个表中选择列

时间:2018-12-18 20:10:04

标签: c# asp.net entity-framework razor-pages

我有以下课程:

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();

2 个答案:

答案 0 :(得分:1)

    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();

答案 1 :(得分:1)

解决方案:

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();