LINQ2EF-LINQ2SQL-LINQ笔记

例1:In

SQL:

Select * from dep where DEP_CLASS=3 AND dep_all_code LIKE '" + depAll + "' AND 
dep_code in (SELECT DISTINCT DEP3 FROM depview WHERE dep3 in (SELECT dep_code 
FROM person_limits WHERE upper(account)='" + UserID + "') )Order By LDAP

LINQ:

 1 IEnumerable<string> dep_codes = perLimRep.GetMany(p => p.ACCOUNT.ToUpper() == UserID).Select(p => p.DEP_CODE);
 2         IEnumerable<string> DEP2s = depvRep.GetMany(d => dep_codes.Contains(d.DEP3)).Select(d => d.DEP3).Distinct().ToArray();
 3         var query = (from d in depRep.GetMany(d => d.DEP_CLASS == 3 && d.DEP_ALL_CODE.StartsWith(depAll))
 4                      select d).OrderBy(d => d.LDAP).ToArray();
 5         var q= (from d in query
 6                where
 7                       DEP2s.Contains(d.DEP_CODE)
 8                select d).OrderBy(d => d.LDAP);
 9         var query2 = (from d in depRep.GetMany(d => d.DEP_CLASS == 3 && depAll.StartsWith(d.DEP_ALL_CODE))
10                       where
11                       DEP2s.Contains(d.DEP_CODE)
12                       select d).OrderBy(d => d.LDAP);
13         var query3 = depRep.GetMany(d=>d.DEP_ALL_CODE.StartsWith(depAll));
14         DataTable dt_dep3 = q.ToDataTable();

例1.1:复杂的in查询 (涉及到字符串拼接而成的SQL)

SQL:

 1         string sCommand = string.Format(
 2              " select dep_code, dep_name from ( "
 3                + " select  *  from dep where dep_code in ( "
 4                    + " select DISTINCT dep_up from dep where dep_code in ( "
 5                         + " select DISTINCT dep_up from dep where dep_code in "
 6                         + "(select dep_code from person_limits where UPPER(account)='{0}'))) "
 7                + " UNION all "
 8                + " select DISTINCT * from dep where dep_code in ( "
 9                    + " select DISTINCT dep_up from dep where dep_code in "
10                         + " (select dep_code from person_limits where UPPER(account)='{0}')) "
11                + " UNION all "
12                + " select DISTINCT * from dep where dep_code in "
13                    + " (select dep_code from person_limits where UPPER(account)='{0}') ) "
14            + " where (dep_show = 1)  ", sUserAccount);
15         if (string.IsNullOrEmpty(sDepClass) == false)
16         {
17             sDepClass = (int.Parse(sDepClass) + 1).ToString();
18             sCommand += " and (dep_class = " + sDepClass + ")";
19         }
20         if (string.IsNullOrEmpty(sDepUp) == false)
21             sCommand += " and (dep_up = " + sDepUp + ")";
22         sCommand += " order by dep_code ";
23 
24         DataTable dt1 = dataProviderCenter.ProduceData(sCommand);
25         if (dt1 != null && dt1.Rows.Count > 0)
26         {
27             foreach (DataRow dRow in dt1.Rows)
28                 sResult += ("" + dRow["dep_code"]).Trim() + "|" +
29                     ("" + dRow["dep_name"]).Trim() + ",";
30         }

LINQ:

 1 IPERSON_LIMITSRepository presonLimitRep = new PERSON_LIMITSRepository(DatabaseFactory.GetFactory());
 2         IDEPRepository depRep = new DEPRepository(DatabaseFactory.GetFactory());
 3 
 4         List<PERSON_LIMITS> listPersonLimit = presonLimitRep.GetMany(p => p.ACCOUNT.ToUpper() == sUserAccount.ToUpper()).ToList();
 5         var deptemp1 = 
 6                         from d4 in (
 7                         (from d2 in
 8                         ((from d1 in depRep.GetManyByClass_LIST(3)
 9                         from p1 in listPersonLimit
10                         where d1.DEP_CODE == p1.DEP_CODE 
11                         select new {DEP_CODE = d1.DEP_UP}).Distinct())
12                         from d3 in depRep.GetManyByClass_LIST(2)
13                         where d3.DEP_CODE == d2.DEP_CODE
14                         select new {DEP_CODE = d3.DEP_UP}).Distinct()
15                         )
16                         from d5 in depRep.GetManyByClass_LIST(1)
17                         where d5.DEP_CODE == d4.DEP_CODE
18                         select d5;
19         var deptemp2 =
20             (from d2 in
21                 ((from d1 in depRep.GetManyByClass_LIST(3)
22                   from p1 in listPersonLimit
23                   where d1.DEP_CODE == p1.DEP_CODE
24                   select new { DEP_CODE = d1.DEP_UP }).Distinct())
25             from d3 in depRep.GetManyByClass_LIST(2)
26             where d3.DEP_CODE == d2.DEP_CODE
27             select d3).Distinct();
28         var deptemp3 =
29             (from d1 in depRep.GetManyByClass_LIST(3)
30              from p1 in listPersonLimit
31              where d1.DEP_CODE == p1.DEP_CODE
32              select d1).Distinct();
33 
34         List<DEP> deptemp = deptemp1.Union(deptemp2).Union(deptemp3)
35             .Where(d => d.DEP_SHOW == 1).ToList();
36         if (string.IsNullOrEmpty(sDepClass) == false)
37             deptemp = deptemp.Where(d => d.DEP_CLASS == (decimal.Parse(sDepClass) + 1)).ToList();
38         if (string.IsNullOrEmpty(sDepUp) == false)
39             deptemp = deptemp.Where(d => d.DEP_UP == sDepUp).ToList();
40         deptemp = deptemp.OrderBy(d => d.DEP_CODE).ToList();

 

例2:Join

SQL:

SELECT DISTINCT dep1  DEP_CODE,depname1  DEP_NAME FROM DepView join PERSON_LIMITS on dep3=dep_code WHERE upper(account)='{0}' ORDER BY DEP_CODE", account.ToUpper()

LINQ:

 var dvPERSON_LIMITS = PERSON_LIMITS_rep.GetManyAccountLIST(account.ToUpper().Trim()).ToList();
            List<string> stPERSON_LIMITS = new List<string>();
            for (int i = 0; i < dvPERSON_LIMITS.Count; ++i)
            {
                stPERSON_LIMITS.Add(dvPERSON_LIMITS[i].DEP_CODE);
            }
            var DEPVIEW_dt = DEPVIEW_rep.GetMany(value => stPERSON_LIMITS.Contains(value.DEP3)).Select(value => new { DEP_CODE = value.DEP1, DEP_NAME = value.DEPNAME1 }).Distinct().OrderBy(value => value.DEP_CODE).ToList();

 例3:ORACLE ROWNUM

SQL:

SELECT HTTP_PATH, FILE_NAME ,FILE_NAME_SOURCE FROM"
                    //+ " ( SELECT * FROM  UPLOAD WHERE SER_NO = :SerNo) WHERE ROWNUM <= 1 ORDER BY ROWNUM ASC

上面的这句SQL其实就是:

elect top 1 HTTP_PATH,FILE_NAME,FILE_NAME_SOURCE from UPLOAD where SER_NO='" + xudaxia.Trim() + "'"

 

LINQ:

第一个需要根据ROWNUM排序,所以Select((x, index) => new { x, index })这句,把index提出来了,原来的结构放在x里面.

第二次的第一个x指的是new { x, index }这个整体,实际的结构是在这个整体中的x里面.

不能在查询表达式中使用select(t, index)这种表达形式的。

var result = from u in ((Entities)this.DataContext).UPLOAD.Where(s => s.SER_NO == serno).Where((s, index) => index <= 1).Select((s, index) => new { s, index }).OrderBy(s => s.index)
                         select new { HTTP_PATH = u.s.HTTP_PATH, FILE_NAME = u.s.FILE_NAME, FILE_NAME_SOURCE = u.s.FILE_NAME_SOURCE };

 为了避免LINQ不识别以上的方法,故改为:

  var result = from u in ((Entities)this.DataContext).UPLOAD.Where(s => s.SER_NO == serno).Select(s => new { s.HTTP_PATH, s.FILE_NAME, s.FILE_NAME_SOURCE }).Take(1)
                         select u;

 例4:查询多字段

SQL:

SELECT ID, panel_name, PIC, Review_PIC, Is_Share, Create_ID, Create_Date, Update_Date, Is_Del, Type_Width, Type_Height FROM PANEL_STYLE where Is_Del='0' and Is_Share='1' and Create_ID <> :UserID ORDER BY Create_ID, Create_Date desc, panel_name

LINQ:

(其实还有一种比较为麻烦的方法,就是先定义一个MOdel Class的类,把属性都COPY都里面。然后在Select new YourClass{xx=u.xx,bb=u.bb...})具体代码不写了,道理都差不多一样)

var result = from p in ((Entities)this.DataContext).PANEL_STYLE.Where(s => s.IS_DEL == 0 && s.IS_SHARE == 1 && s.CREATE_ID != uid).Select(u => new { u.ID, u.PANEL_NAME, u.PIC, u.REVIEW_PIC, u.IS_SHARE, u.CREATE_ID, u.CREATE_DATE, u.UPDATE_DATE, u.IS_DEL, u.TYPE_WIDTH, u.TYPE_HEIGHT })
                         orderby p.CREATE_ID, p.CREATE_DATE descending, p.PANEL_NAME
                         select p;

 例5:LINQ做符号运算(多字符串拼接的SQL)

1             if (!string.IsNullOrEmpty(sYear)) commYear = " AND ACTION_YEAR='" + sYear.Trim() + "' ";
2             if (!string.IsNullOrEmpty(sQuarter)) commQuarter = " AND ACTION_QUARTER='" + sQuarter.Trim() + "' ";
3             if (!string.IsNullOrEmpty(sMonth)) commMonth = " AND ACTION_MONTHS='" + sMonth.Trim() + "' ";
4             if (!string.IsNullOrEmpty(sWeekY)) commWeekY = " AND ACTION_WEEK_BYYEAR='" + sWeekY.Trim() + "' ";
5             if (!string.IsNullOrEmpty(sWeekM)) commWeekM = " AND ACTION_WEEK_BYMONTHS='" + sWeekM.Trim() + "' ";
6             if (!string.IsNullOrEmpty(sDate)) commDate = " AND to_date(Action_Date,'yyyy-mm-dd hh24:mi:ss')=to_date('" + sDate.Trim() + "','yyyy-mm-dd hh24:mi:ss') ";
7             string strComm = "SELECT (sum(Call_No)-sum(UnCall_No)) SumCallNo ,sum(Process_Time_Total)  SumProcessTime ,sum(Wait_Time_Avg*(call_no - uncall_no))  SumWaitTime ,max(Wait_People_Max)  MaxWaitPeople ";
8             strComm += " FROM branch_comparison_bykind WHERE BRANCH_ID='" + sDep.Trim() + "' " + commYear + commQuarter + commMonth + commWeekY + commWeekM + commDate;

LINQ:

1  public IQueryable<dynamic> GetDetailInfo(string sdep,decimal sYear,decimal sQuarter,decimal sMonth,decimal sWeekY,decimal sWeekM,string sDate)
2         {
3             var bcList=((Entities)this.DataContext).BRANCH_COMPARISON_BYKIND.ToList();
4             var result = from b in bcList.Where(s => s.BRANCH_ID == sdep && s.ACTION_YEAR == sYear && s.ACTION_QUARTER == sQuarter && s.ACTION_MONTHS == sMonth && s.ACTION_WEEK_BYYEAR == sWeekY && s.ACTION_WEEK_BYMONTHS == sWeekM && s.ACTION_DATE == sDate).Select(b => new { SumCallNo = bcList.Sum(s => s.CALL_NO) - bcList.Sum(s => s.UNCALL_NO), Process_Time_Total = bcList.Sum(s => s.PROCESS_TIME_TOTAL), SumWaitTime = bcList.Sum(s => s.WAIT_TIME_AVG * (s.CALL_NO - s.UNCALL_NO)), MaxWaitPeople = bcList.Max(s => s.WAIT_PEOPLE_MAX) })
5                          select b;
6             return result as dynamic;         
7         }

 

posted @ 2014-04-15 16:30  许大虾  阅读(611)  评论(0编辑  收藏  举报