2014-02-19 28 views
0

我有如下實體框架模型和數據在相應的數據庫表:實體框架查詢 - 從子表中返回唯一行

enter image description here

問題:我如何查詢模型返回所有與給定person相關的行(完整實體,非匿名類型)sales_type

如果數據如上,那麼約翰,查詢應從sales_type - 表和馬克它應該返回的行2和5

+0

您是否在尋找每條記錄的長單行? – Miller

回答

0

像這樣的事情

ctx.PersonSales 
    .Where(ps=> ps.Person.Id = myPersonId) 
    .Where(ps=> ps.SalesMapping != null && ps.SalesMapping.SalesType != null) 
    .Select(ps=>ps.SalesMapping.SalesType) 
    .Distinct(); 
返回排前三
0

也許是這樣的:

var personId=1; 
var result= (
     from salesType in db.sales_type 
     where 
      (
       from salesMapping in db.sales_mapping 
       join personSale in db.person_Sales 
        on salesMapping.id equals personSale.sales_mapping_id 
       join person in db.person 
        on personSale.person_id equals person.id 
       where 
        person.Id == personId 
       select salesMapping.sales_type_id 
      ).Contains(salesType.id) 
     select salesType 
    ).ToList(); 

其中db是LINQ數據上下文