对LinQ的简单SQL查询,我已经尝试但尚未解决

时间:2015-12-10 04:56:49

标签: c# sql-server linq

我有以下SQL Server查询,我需要在LINQ,简单查询中使用它,但我尝试了几次,但我无法让它工作。

这是SQL查询

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%'
    ) 

我尝试过这个查询,但我仍感到困惑

var account=from acc in currentDB.td_Accountline
                                              where acc.BonusPlan.BonusPlanID == 1 && acc.Amount > 0 && acc.Ord_Sub_ID.Contains("SMPORD") && acc.Created.ToDateTime().Month == 11 && acc.Created.ToDateTime().Year == 2013
                                              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("SMPORD")
                                              select acc; 

我想要一个查询,请不要单独查询以减少数据库调用。

3 个答案:

答案 0 :(得分:2)

我想你差不多了。而不是:

where !accNot.Contains("SMPORD")

应该是:

where !accNot.Contains(acc.Ord_Sub_ID)

您最终的Linq查询将是:

var account = from acc in currentDB.td_Accountline
              where 
                acc.BonusPlan.BonusPlanID == 1
                && acc.Amount > 0
                && acc.Ord_Sub_ID.Contains("SMPORD")
                && acc.Created.Month == 11 
                && acc.Created.Year == 2013
              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; 

答案 1 :(得分:0)

正则表达式在Linq for Entity Framework中无法正常工作,但您可以在内存列表中转换为集合,以便使用Regex。 像这样:

(from x in td_Accountline where Created.Month = 11 && Created.Year = 2013 select a).ToList().Where(v => Regex.IsMatch(v.Ord_Sub_ID,@"(SMPORD)"))

这样,匹配将在内存中发生

答案 2 :(得分:0)

试试这个:

var Ord_Sub_IDs = from n in td_Accountline where n.BonusPlanID == 3 && n.Ord_Sub_ID.Contains("SMPORD") select n.Ord_Sub_ID ;

var result=from n in td_Accountline where n.BonusPlanId == 1 && n.Amount > 0 && n.Ord_Sub_ID.Contains("SMPORD") && n.Created.ToDateTime().Month == 11 && n.Created.ToDateTime().Year == 2013 && Ord_Sub_IDs.Contains(td.Ord_Sub_ID) select n;