【问题标题】:Return one column from navigation table in my lambda linq query by .include()通过 .include() 从我的 lambda linq 查询中的导航表中返回一列
【发布时间】:2020-01-09 05:07:21
【问题描述】:

我使用这个 lambda linq 查询以列表形式从数据库中检索数据:

return _context.BaseCompanies.Where(x => x.Active)
            .Include(b => b.BaseCity)
            .Include(b => b.BaseCompanyGroupFour)
            .Include(b => b.BaseCompanyGroupOne)
            .Include(b => b.BaseCompanyGroupThree)
            .Include(b => b.BaseCompanyGroupTwo)
            .Include(b => b.BaseCompanyTitle)
            .Include(b => b.BaseCompanyType)
            .Include(b => b.BaseCountry)
            .Include(b => b.BaseProvince).ToList();

记录是10条记录但是和另一个表有很多关系,我也想使用相关表中的数据,为此使用.include(),但是当我使用.Include()时,它返回相关表中的所有数据并通过这种关系从数据库中返回更多不必要的数据。

例如从表City,我只需要城市名称,但返回IdNameCreateDate,...

我如何才能从包含包含的表城市中仅检索城市的Name

【问题讨论】:

    标签: c# linq asp.net-core-mvc relational-database


    【解决方案1】:

    你需要使用Select来重塑数据:

    return await _context.BaseCompanies.Where(x => x.Active).Select(x =>
    {
        SomePropOnBaseCompany = x.SomePropOnBaseCompany,
        SomePropOnBaseCity = x.BaseCity.SomePropOnBaseCity,
        // etc.
    }).ToListAsync();
    

    如果您专门从相关实体中选择道具,则根本不需要 Include 调用。 EF 将自动发出连接以填充您请求的数据。只需列出您要提取的属性即可。

    【讨论】:

      【解决方案2】:

      您可以使用Select 返回任何列并返回为List<BaseCompany>

      var p = _context.BaseCompanies.Select(bp => new BaseCompany
              {
                  //your custom fields
                  Id = bp.Id,
                  Description = bp.Description,
      
                  //for one-to-one relationship
                  BaseCity = new City()
                  {
                      Name = bp.BaseCity.Name
                  },
      
                  //for one-to-many relationship
                  BaseCity = bp.BaseCity.Select(city=> new City
                  {
                      Name = city.Name
                  }).ToList()
              }).ToList();
      

      【讨论】:

        猜你喜欢
        • 2018-06-09
        • 2021-07-11
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 1970-01-01
        • 2018-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多