LINQ To EF


1. 簡單查詢

                var result = from c in db.Customers select c;

2. 條件查詢

   普通 LINQ 寫法:

                var result = from c in db.Customers where c.Country == "UK" select c;

   Lambda 表達式寫法:

                var result = db.Customers.Where(c => c.Country == "UK");

3. 排序分頁

                IQueryable<Customers> cus10 = (from c in result orderby c.CustomerID select c).Skip(0).Take(10);

4. 聚合

            using (var edm = new NorthwindEntities())
            {
                var maxuprice = edm.Products.Max(p => p.UnitPrice);
                Console.WriteLine(maxuprice.Value);
            }

5. 連接

    可以使用的連接有 Join 和 GroupJoin 方法。

    GroupJoin 組連接等效於左外連接,返回第一個(左側)數據源的每個元素(即使其他數據源中沒有關聯元素)。

            using (var edm = new NorthwindEntities())
            {
                var query = from d in edm.Order_Details
                            join order in edm.Orders                //重點
                            on d.OrderID equals order.OrderID       //重點
                            select new              //這也是重點
                            {
                                OrderId = order.OrderID,
                                ProductId = d.ProductID,
                                UnitPrice = d.UnitPrice
                            };

                foreach(var q in  query)
                {
                    Console.WriteLine("{0},{1},{2}", q.OrderId, q.ProductId, q.UnitPrice);
                }
            }

    EF 不支持復雜類型(如實體)的直接檢索,只能用簡單類型,比如常用的標量類型 string、int 和 guid。(即說的是可以是 c == "",但不可以是 c == 某個實體類對象)

    如果出現此錯誤,會引發 NotSupportedException 異常,並顯示消息 “無法創建 ‘System.Object’ 類型的常量值”。

6. 分組查詢

            using (var db = new NorthwindEntities())
            {
                var query = from c in db.Categories
                            join p in db.Products
                            on c.CategoryID equals p.CategoryID
                            group new { c, p } by new { c.CategoryName } into g
                            select new
                            {
                                g.Key.CategoryName,
                                SumPrice = (decimal?)g.Sum(pt => pt.p.UnitPrice),
                                Count = g.Select(x => x.c.CategoryID).Distinct().Count()
                            };
            }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM