Thursday, December 10, 2015

SQL query to LinQ sub query simple tricks


I have the following SQL query and I will change it in LINQ, Simple query but have to do in one query to reduce database call. Here is the SQL query
select * from td_Accountline 
where 
    BonusPlanID = 1
    and Amount > 0
    and Ord_Sub_ID like '%SMPORD%' 
    and MONTH(Created) = 11
    and YEAR(Created) = 2013  
    and Ord_Sub_ID not in (
        select Ord_Sub_ID 
        from td_Accountline 
        where 
            BonusPlanID =3 and
            Ord_Sub_ID like '%SMPORD%'
    ) 

My LinQ query is bellow, I have used 'let'. The 'Let' keyword allows storing the results of a query which can be used in a subsequent query.
  var accountdata = from acc in currentDatabase.td_Accountline 
                    where
                    acc.BonusPlan.BonusPlanID == 1
                    && acc.Amount > 0
                    && acc.Ord_Sub_ID.Contains("SMPORD")
                    && acc.Created.Value.Month == 11
                    && acc.Created.Value.Year == 2015
                    let accNot = from accN in currentDatabase.td_Accountline 
                                 where
                                 accN.BonusPlan.BonusPlanID == 3
                                 && accN.Ord_Sub_ID.Contains("SMPORD")
                                 select accN.Ord_Sub_ID
                             where !accNot.Contains(acc.Ord_Sub_ID)
                    select acc;


Happy LinQ Sub Query :)

No comments:

Post a Comment