【问题标题】:Select column from another table based on Id using Entity Framework使用实体框架根据 Id 从另一个表中选择列
【发布时间】:2019-05-19 07:15:27
【问题描述】:

我有以下课程:

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

【问题讨论】:

  • 你有带 BlogCategory 和 Blog 的导航属性吗?
  • 您的意思是 CatId 吗?我有公共虚拟博客 {get; set;} 在 BlogCategory 中
  • 是的,但您并没有实际告诉 EF CatId 是您发布的内容的外键
  • 那么,如果您只需要一个类别名称,您是否可以复制此属性并将其也包含在 Blog 类中?另一种选择是使用 sql 连接并获取包含类别名称的自定义对象。
  • @Ramūnas,我有身份证,为什么要有名字?不好

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


【解决方案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();

【讨论】:

  • 谢谢,我想避免使用连接样式,实际上我解决了它并在上面发布了解决方案。
【解决方案2】:

解决方案:

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

【讨论】:

    猜你喜欢
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 2013-01-25
    • 2012-03-23
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多