2012-08-16 106 views
-4

,因爲我需要正如我tryed與IQueryable的,但沒能做到以下MS SQL查詢轉換中的LINQ C#如果IQueryable的條件LINQ查詢加入(轉換SQL到LINQ)

正如我們需要檢查,如果條件爲真,那麼只需要去同臺參加進階

感謝。

SELECT @sqlQuery = 'SELECT distinct tbl_1.col1 , tbl_1.col2, tbl_1.col3 
    FROM tbl_1 vd '   

if(@Condetion is not null)   
BEGIN   
    set @sqlQuery = @sqlQuery +' 
    Inner Join   
    (SELECT vml.*   
     FROM tbl_2 vml   
     INNER JOIN tbl_3 vm   
     ON tbl_1.IDCol = tbl_2.IDCol WHERE tbl_3.Name LIKE ''%'[email protected]+'%'') A ON A.MessageID = vd.MessageID '   
END   

    set @sqlQuery = @sqlQuery + 'INNER JOIN tbl_4 tbl 
    ON tbl.ColID12 = vd.ColID12 
    LEFT OUTER JOIN    
     vdd_typeid tblVdd ON tblVdd.TypeId=tbl_1.TypeId    
INNER JOIN ...... ' 

EXEC sp_executesql @sqlQuery 

正如下面我有LINQ嘗試

var query = from VD in _db.GetTable<tbl_1>() select VD ; 

      if (!string.IsNullOrEmpty(Category.Trim())) 
      { 
       query = query.Join((from VML in this._db.GetTable<tbl_1>() 
             join VM in this._db.GetTable<tbl_2>() on VML.MessageID equals VM.MessageID 
             where VM.Category.Name(Condetion),VD => new{VD.TypeId == [need write to write like this but can not VML.TypeId] } 

      } 

      query = query.Join(from TblVMS_def in this._db.GetTable<tbl_4>() on ........ 
+2

我們可以,如果你能爲我們提供了LINQ的實體,你有沒有關聯建立? – 2012-08-16 14:02:38

+0

你真的使用實體框架或LINQ 2 SQL嗎? – vittore 2012-08-16 14:04:01

+0

此外,您的子查詢是非常混亂,並不清楚,如果你有3個表共享相同的密鑰或三個表中的一個持有2個鍵,而兩個表只有一個等 – vittore 2012-08-16 14:08:25

回答

1

這是非常難deciper你真正需要的,我了個去這裏,但有可能要簡單得多與副本您的實體圖以及您之後數據的簡要說明。

我了個去什麼我想你想

var cat = string.IsNullOrWhiteSpace(Category) ? null : Category.Trim(); 
var query = from VD in _db.GetTable<tbl_1>() 
      join tbl in _db.GetTable<tbl_4>() on tbl.ColID12 equals VD.ColID12 
      join VM_I in _db.GetTable<tbl_2>() on VD.MessageID equals VM_I.MessageID 
      from VM in VM_I.DefaultIfEmpty() 
      where cat == null || VM.Category.Name.Contains(cat) 
      select new { col1 = VD.col1, col2 = VD.col2, VD.col3 }; 

你可以那麼對於不同的值做query.Distinct();

我可以建議你使用LinqPad制定出您的查詢,所以可以非常容易與工作,也將顯示你所得到的SQL