2014-08-27 75 views
0

我有3个表(无论是在我的OR映射模型中的对象)。我们称它们为TABLE1,TABLE2和TABLE3 =>实际名称是捷克语,我认为这会比较好。所有组合 - LINQ查询

1)TABLE1与TABLE2具有1-N关系。 2)TABLE1与TABLE3也有1-N的关系。因此,表是这个样子:

TABLE2 
    { 
     int ID; 
     nvarchar attributeT2; 
     int TABLE1_FK; 
    } 

    TABLE1 
    { 
     int ID; 
    } 

    TABLE3 
    { 
     int ID; 
     nvarchar attributeT3 
     int TABLE1_FK; 
    } 

现在我需要的所有组合:TABLE2记录,其中attributeT2 ==“T2”和表3记录,其中attributeT3 ==“T3”但是这两个必须具有相同的TABLE1_FK( =它们必须由TABLE1记录加入)。

因此,如果TABLE2中有2条记录与TABLE1_FK == 1,TABLE3_FK == 1的TABLE3中有2条记录,那么我需要所有组合== 4对。我可以通过foreach循环来做到这一点,并在每一步查询数据库,但我认为这将是非常无效的,我想知道是否有更好的方法。

我想这可能是这样的:

var query= from x in context.TABLE2 
       where x.attributeT2 == "T2" 
       join y in context.TABLE3 on x.TABLE1_FK == y.TABLE1_FK 
       where y.attributeT3 == "T3" 
       select new WrapperClass(x,y); 

但组合是错误的 - 这对并不总是具有相同的TABLE1_FK。万分感谢您的回复。

回答

0

我没有自己检查,但可能值得尝试。这样做是为了参加在表2中和表3 FK列和具有地方条件attibuteT3和attributeT2

var query= from x in context.TABLE2 
      join y in context.TABLE3 on x.TABLE1_FK == y.TABLE1_FK 
      where y.attributeT3 == "T3" && x.attributeT2 == "T2" 
      select new WrapperClass(x,y); 
0

我很抱歉,但2分钟后,我会点击提交按钮,我想的东西,我的避风港没有试过。

 var asdf = from x in context.TABLE1 
        join y in context.TABLE2 on x.ID equals y.TABLE1_FK 
        where y.attributeT2 == "T2" 
        join z in context.TABLE3S on x.ID equals z.TABLE1_FK 
        where z.attributeT3 == "T3" 
        select new WrapperClass(y,z); 

它工作。无论如何感谢迈克尔。