-4

As I need to convert following MS SQL Query in to Linq in C#

As I have tryed with IQueryable but not able to do .

As in that we need to check if condition is true then only need to go for join with table

Thanks in adv.

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 ''%'+@Condetion+'%'') 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

As following i have try with 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 ........
4

1 回答 1

1

It is extremely hard to deciper what you actually need, I've had a go here but it would possibly be far simpler with a copy of your Entity Diagram and a concise description of the data you are after.

I've had a go with what I think you want

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 };

you can then do query.Distinct() for distinct values;

Can I suggest that you use LinqPad to work out your query, it's far easier to work with and will also show you the resulting SQL

于 2012-08-16T16:31:09.033 回答