2013-10-29 219 views
1

我有三個表中的多對多關係。它們是:實體框架LINQ多對多查詢

  • t033_region
  • t031_geocode
  • t032_region_to_geocode_mapping

我使用實體框架,並與IQueryable的GetItems)倉庫模型(。如何檢索給定區域ID(t033)的所有地理編碼(t031)條目?我有效地想說:

SELECT * FROM t031_geocode其中t031_id在

但是(從t032_region_to_geocode_mapping其中t033_id = @RegionId選擇t031_id)我怎麼說這個使用實體框架和LINQ?我想它始於:

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

但是在Where子句中做什麼表達式去做?還是有更好的方法來完成我正在做的事情?

回答

4

的方式,我通常會做這樣的事情是首先得到要匹配,然後得到的匹配這些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); 
0

這是取決於你的存儲實施?!

這應該尋找這樣的:

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