Linq 连接查询返回空数据集

Linq Join query returning empty dataset

我正在使用下面的代码根据 officeId 字段加入两个 table。正在重新调整 0 条记录。

  IQueryable<Usage> usages = this.context.Usage;
  usages = usages.Where(usage => usage.OfficeId == officeId);

  var  agencyList = this.context.Agencies.ToList();
  var usage = usages.ToList();
  var query =  usage.Join(agencyList,
                                     r => r.OfficeId,
                                     a => a.OfficeId,
                                     (r, a) => new UsageAgencyApiModel () { 
                                            Id = r.Id,
                                            Product = r.Product,
                                            Chain = a.Chain,
                                            Name = a.Name
                                     }).ToList();

我在机构中有 1000 多条记录 table,在使用中有 26 条记录 table。

我期待 26 条记录作为结果,chainname 列附加到机构 table 的结果。

它没有返回任何东西。我是 .net 的新手,如果我遗漏了什么,请指导我

EDIT

@Tim Schmelter 的解决方案如果我在执行连接时同时获得两个 table 上下文,则效果很好。但是在应用 join

之前,我需要在 usage table 之上添加过滤器
 IQueryable<Usage> usages = this.context.Usage;

usages = usages.Where(usage => usage.OfficeId == officeId);

 
            var query = from a in usages 
           // works with this.context.usages instead of usages
            join u in this.context.Agencies on a.OfficeId equals u.OfficeId
            select new  
            { 
               Id = a.Id,
               Product = a.Product,
               Chain = u.Chain,
               Name = u.Name
            };
return query.ToList();

在此处附上屏幕截图

相同的连接查询可以很好地处理内存数据,如下所示

如果我直接添加内存数据源或两个数据源,这两种方式都可以正常工作。但是,如果我在应用连接查询

之前基于 officeIdusages 上添加过滤器,则无法正常工作

一个问题是您首先将所有内容加载到内存中(ToList())。

对于连接,我更喜欢查询语法,它不那么冗长:

var query = from a in this.context.Agencies
            join u in this.context.Usage on a.OfficeId equals u.OfficeId
            select new UsageAgencyApiModel() 
            { 
               Id = u.Id,
               Product = u.Product,
               Chain = a.Chain,
               Name = a.Name
            };

List<UsageAgencyApiModel> resultList = query.ToList();

编辑:您应该可以在 Join 之后应用 Where。如果您仍然没有得到记录,则没有匹配项:

var query = from a in this.context.Agencies
            join u in this.context.Usage on a.OfficeId equals u.OfficeId
            where u.OfficeId == officeId
            select new UsageAgencyApiModel{ ... };

下面的代码可以帮助获取基于 ID 值的输出。

当然是用Lambda写的

var officeId = 1;
var query = context.Agencies    // your starting point - table in the "from" statement
   .Join(database.context.Usage, // the source table of the inner join
      agency => agency.OfficeId,        // Select the primary key (the first part of the "on" clause in an sql "join" statement)
      usage  => usage.OfficeId ,   // Select the foreign key (the second part of the "on" clause)
      (agency,  usage) => new {Agency = agency, Usage = usage }) // selection
   .Where(x => x.Agency.OfficeId == id);    // where statement