Linq查询从两个表中删除重复的行

时间:2014-02-06 14:22:36

标签: c# sql linq

我有两个表Table_Access1和Table_Access 2。

----------------------------------------
Access_ID | Entity_ID | Entity_LookupID
----------------------------------------
   1      |   4       |  1
----------------------------------------
   2      |   4       |  2
---------------------------------------
   3      |   4       |  10
----------------------------------------  
__________________________________________

----------------------------------------
Access_ID | Entity_ID | Entity_LookupID
----------------------------------------
  0      |   4       |  1
----------------------------------------
   0      |   4       |  2
---------------------------------------
   0     |   4       |  11
---------------------------------------- 
   0     |   4       |  13
---------------------------------------- 

______________________________________

结果表:

----------------------------------------
Access_ID | Entity_ID | Entity_LookupID
----------------------------------------
  0      |   4       |  11
----------------------------------------
   0      |   4       |  13
---------------------------------------

对于TBL_Access1Access_ID是主键,TBL_Access2是来自DTO且没有Access_ID的对象。我想从Table_Access 2插入不重复的行。 Entity_IDEntity_LookupID的组合将是唯一的。结果表是我正在寻找的输出。

我正在努力与linq查询,任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:0)

from t2 in Table_Access2
//join t1 in Table_Access1 on t2.Entity_ID = t1.Entity_ID
from t1 in Table_Access1
where (t2.Entity_ID == t1.Entity_ID && t2.Entity_LookupID != t1.Entity_LookupID)
      || (t2.Entity_LookupID == t1.Entity_LookupID && t2.Entity_ID != t1.Entity_LookupID)
      || (t2.Entity_LookupID != t1.Entity_LookupID && t2.Entity_ID != t1.Entity_LookupID)
      )
select t2

答案 1 :(得分:0)

这不是linq,但由于它们是数据库表,你可以

 SELECT * FROM TBL_Access1 LEFT JOIN TBL_Access2 
     ON ( TBL_Access1.Entity_ID <> TBL_Access2.Entity_ID 
          AND TBL_Access1.Entity_LookupID <> TBL_Access2.Entity_LookupID )  
     OR ( TBL_Access1.Entity_ID <> TBL_Access2.Entity_ID 
          AND TBL_Access1.Entity_LookupID = TBL_Access2.Entity_LookupID ) 
     OR ( TBL_Access1.Entity_ID = TBL_Access2.Entity_ID 
          AND TBL_Access1.Entity_LookupID <> TBL_Access2.Entity_LookupID )

答案 2 :(得分:0)

不使用任何应该为你需要的东西工作。虽然您的请求似乎想要来自table1的第3条记录。

var query = TBL_Access2
            .Where(t2 => !TBL_Access1
            .Any(t1 => t1.Entity_ID == t2.Entity_ID && t1.Entity_LookupID == t1.Entity_LookupID));

答案 3 :(得分:0)

当我使用以下内容时工作:

var userAccessInsert = (from r in TBL_Access2
                                where !(from uA in TBL_Access1
                                       where uA.Entity_LookupID == r.Entity_LookupID
                                       select uA.Entity_LookupID).Contains(r.Entity_LookupID)
                                       select r);

全部感谢您的输入。