2016-10-01 107 views
1

我只有LINQ的基礎知識。我講SQL和JDBC,負責將動態PL/SQL轉換爲LINQ Entity Framework。我如何將條件WHERE子句添加到LINQ查詢中?這裏是一個非常簡單的例子(留出類型的信息):動態SQL到LINQ實體框架

Q1 := 'SELECT bDay = b.birthday 
      address = b.address 
     FROM (' ; 

Q2 := 'SELECT folks.birthday, Address.address 
     FROM folks, 
      (SELECT state, 
        surname AS name 
      FROM Individuals, Addresses 
      WHERE Individuals.addrId = Address.id 
      AND Addresses.state = 'CA') find1 
      ,(SELECT state, 
        surname AS name 
      FROM Individuals, Addresses 
      WHERE Individuals.addrId = Address.id 
      AND Addresses.state = 'NV') find2 
    AND find1.state(+) = folks.state'; 

IF input_parm = 'RED' THEN 
    condAddOn :=condAddOn || 'AND folks.vacationHouse IS NOT NULL'; 
END IF; 
IF input_parm = 'BLUE' THEN 
    condAddOn :=condAddOn || 'AND folks.vacationHouse = 'Cabin'; 
END IF; 
... 
OPEN curs FOR Q1 || Q2 || condAddOn ')b'; 

試圖找出C#/ LINQ的語法,這是我嘗試(工作自下而上):

var find1 = (from addr in Addresses 
      from indiv in Individuals 
      where indiv.addrId = addr.addrID 
      select new 
      { 
       indiv.state, 
       indiv.surname 
      }); 

var find1OuterJoin = (from person in folks 
         join f1 in find1 on person.addrId equals f1.addrID 
         from f1OutJn in temp.DefaultIfEmpty() 
         select new 
         { 
         f1OutJn.state, 
         f1OutJn.surname 
         }); 

var Q2 = (from person in folks 
      from addr in addresses 
      from f1 in find1OuterJoin 
      where person.addrId == addr.addrId 
      && f1.state == folks.state 
      select new 
      { 
      person.birthday 
      ,addr.address 
      }); 

var Q1 = (from q2 in Q1 
      select new 
      {bDay = b.birthday 
      ,address = b.address 
     }); 

我不知道 1)如果我介紹Q1到Q2正確 2)如何引入動態WHERE子句 到具有等同光標語句結束:

OPEN curs FOR Q1 || Q2 || condAddOn ')b'; 

添加:我可以使用函數或表達式來包含動態位嗎?我看到了對Expression和Expandable()的引用,但不確定。 添加:我嘗試在LINQ查詢

回答

2

當使用帶鏈接的where方法時,您將返回一個IQueryable對象。使用lambda LINQ,你也可以使用AsQuerably擴展方法,尤其是當

var results = from person in folks 
       join addr in addresses 
       where person.addrId == addr.addrId 
       select new { 
        person.birthday, 
        addr.address 
        }; 
if(predicate){ 
    results = from r in results 
       where /* new condition here */ 
       select r; 
} 
var resultSet = results.ToList().AsEnumerable(); 

其它鏈接運營商:這不立即執行語句,因此可以做到以下幾點。

如,但不限於:

var results = folks.join(address, 
       person => person.addrId, 
       addr => addr.addrId 
       (person, addr) => new { 
              person.birthday, 
              addr.address 
             }).AsQueryable(); 
if(predicate) 
{ 
    results = results.where(/*predicate for the where condition*/); 
} 
var resultSet = results.ToList().AsEnumerable(); 
+0

謝謝你的解釋。我認爲這會讓我開始:-) – frododot