2013-07-29 51 views
1

我從web表單項目中選擇了這個選項,我想將其轉換爲我可以在我的mvc項目中使用以顯示在剃鬚刀頁面中的下拉列表中將sql語句轉換爲lambda以在剃鬚刀頁面中使用

<asp:SqlDataSource ID="Sections" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnection %>" 
       SelectCommand="SELECT e.DisplayName, e.ID , e.GUID 
       FROM Table1 e 
       INNER JOIN RootTables re 
       ON e.ID = re.Table1ID 
       AND re.ChairID = 1"> 
      </asp:SqlDataSource> 

我想到它開始像:var sCommand = (from e in Table1....);

+1

只是你要求的是一個等效的LINQ to SQL語句。 lambda表達式只是LINQ表達式的'x => x ...'部分。這實際上只是一個匿名函數,你傳遞給查詢函數(select,where,e​​ct)。 – evanmcdonnal

回答

4

這是很簡單的。查詢應該是這樣的:

var results = 
    from e in db.Table1 
    join re in db.RootTables re 
    on e.ID equals re.Table1ID 
    where re.ChairID == 1 
    select new { e.DisplayName, e.ID, e.GUID }; 

或者用流利的語法:

var results = 
    db.Table1.Join(db.RootTables, 
     e => new { e.ID, ChairID = 1 }, 
     re => new { ID = re.Table1ID, re.ChairID }, 
     (e, re) => new { e.DisplayName, e.ID, e.GUID }); 

如果你適當的設置您的導航性能,它變得更簡單:

var results = 
    from e in db.Table1 
    where e.RootTables.Any(re => re.ChairID == 1) 
    select new { e.DisplayName, e.ID, e.GUID }; 

或者流利的語法:

var results = db.Table1.Where(e => e.RootTables.Any(re => re.ChairID == 1)) 
         .Select(e => new { e.DisplayName, e.ID, e.GUID }); 
+0

這是正確的,但前提是數據不是通過Entity Framework或任何其他ORM訪問的,通常情況並非如此。如果使用實體框架,則不需要連接。 – ataravati

+1

@ataravati寫入連接並沒有讓它更不正確。如果您使用的是ORM,則LINQ提供程序會推斷該聯接。連接是必需的,並且將以任何方式在生成的SQL中。 – evanmcdonnal

+1

@ataravati它仍然可以與EF /任何其他ORM一起使用,但是你是對的,如果有合適的導航屬性,則不需要連接。我提供了一個可以在這種情況下工作的備用版本。 –