实体框架 LINQ 多对多查询

本文关键字:查询 LINQ 框架 实体 | 更新日期: 2023-09-27 18:37:12

我在多对多关系中有三个表。这些是:

  • t033_region
  • t031_geocode
  • t032_region_to_geocode_mapping

我正在使用带有IQueryable GetItems()的实体框架和存储库模型。如何检索给定区域 ID (t033) 的所有地理编码 (t031) 条目?我实际上想说:

从t031_geocode t031_id中选择 *(从t032_region_to_geocode_mapping中选择 t031_id,其中 t033_id = @RegionId)

但是,如何使用实体框架和 LINQ 来说明这一点呢?我想它始于:

var data = _repository.GetItems<t031_geo_code>().Where(g => ???);

但是,在 Where 子句中用什么表达式来执行上述操作?或者有没有更好的方法来完成我正在做的事情?

实体框架 LINQ 多对多查询

我通常做这种事情的方式是首先获取要匹配的 id 列表,然后获取与这些 id 匹配的记录子集,如下所示:

var ids = _repository.Get<t032_region_to_geocode_mapping>().Where(x => x.t33_id = @RegionId).Select(x => x.t03_id).ToList();
var data = _repository.Get<t031_geocode>().Where(x => ids.Contains(x.t031_id);
这取决于

你的后验实现?!

这里它应该看起来像这样:

var regionKeyOrKeys = new int []{XX};
var codes = (from region in t031_geocode.GetAllItems..// Get all items no problem here! because of 
          where (regionKeyOrKeys.Contains(region.Key)) 
          select region).ToList();