Quantcast sort data in entity framework

sort data in entity framework

by Neon Quach 30. November 2010 22:30

Trong bài blog này mình sẽ hướng dẫn mọi người phương pháp sắp xếp (Sort) dữ liệu sử dụng các công nghệ truy vấn Entity Framework, snippets code trong ví dụ sẽ trả về  tập hợp đối tượng Contact trong table Contact của CSDL AdventureWork bao gồm các cách: LINQ to Entities, Entity SQL with ObjectQuery<T>, Query builder methods of ObjectQuery<T> và Dynamic LINQ OrderBy.

Để cho đơn giản mình sẽ tạo 1 simple console application sử dụng both C# và VB.NET

Sau khi tạo xong mình sẽ add ADO.NET Entity Model và named AdventureWorks.edmx

Màng hình kế tiếp là Model được generate từ Database có sẳn hay chưa có, ở đây mình dùng CSDL AdventureWorks nên mình chọn Generate From Database, hẹn các bạn bài sau mình sẽ hướng dẫn cách làm việc với option Empty model này



Màng hình tiếp theo có 2 options liệu password connect tới database có được includes và file config hay không, nếu không thì chúng ta sẽ phải tự viết code conect tới db và truyền vào password login vào db, ở đây mình sẽ chọn include password vào config file.



Tất cả các objects của database AdventureWorks sẽ được hiển thị ở đây, mình sẽ chọn table Contact



Click Finish màng hình surface sẽ hiển thị Contact table



Okie mọi thứ đã sẳn sàng, giờ tới phần code

Cách 1: Sử dụng LinqToSql

        private static void LinqToEntity()
        {
            using (AdventureWorksEntities context = new AdventureWorksEntities())
            {
                // Define a query that returns a list 
                // of Contact objects sorted by last name.
                var sortedNames =
                    from n in context.Contacts
                    orderby n.LastName
                    select n;

                Console.WriteLine("The sorted list of last names:");
                foreach (Contact name in sortedNames)
                {
                    Console.WriteLine(name.LastName);
                }
            }
        }

Giải thích dòng code:
Bởi việc bọc using cho object AdventureWorksEntities, đảm bảo object sẽ đượcc Dispose khi thoát khỏi hàm, sau đó mình dùng Linq để select Contact, then mình sẽ order theo Lastname.
Vòng lặp foreach qua danh sách Contact, sau đó hiển thị lên màng hình tên của Contact đó.

Sau đó gọi hàm LinqToEntity trong hàm Main, và nhấn F5 xem kết quả

Cách 2: sử dụng EntitySql

        private static void EntitySql()
        {
            // Define the Entity SQL query string that returns 
            // Contact objects sorted by last name.
            string queryString = @"SELECT VALUE contact FROM Contacts AS contact Order By contact.LastName";
            using (AdventureWorksEntities context = new AdventureWorksEntities())
            {
                ObjectQuery<Contact> query = new ObjectQuery<Contact>(queryString, context);

                Console.WriteLine("The sorted list of last names:");
                foreach (Contact name in query.Execute(MergeOption.AppendOnly))
                {
                    Console.WriteLine(name.LastName);
                }
            }
        }

Giải thích: Thay vì phải sử dụng LinqToEntity, bởi việc sử dụng Object Services của Entity Framework (trong namespace System.Data.Objects) trực tiếp, chúng ta có thể tạo ObjectQuery trực tiếp kết hợp với T-SQL của Entity Framework gọi là Entity Sql để build query expression


Cách 3: QueryBuilder

        private static void QueryBuilder()
        {
            using (AdventureWorksEntities context = new AdventureWorksEntities())
            {
                ObjectQuery<Contact> query = context.Contacts.OrderBy("it.LastName");
                Console.WriteLine("The sorted list of last names:");
                foreach (Contact name in query.Execute(MergeOption.AppendOnly))
                {
                    Console.WriteLine(name.LastName);
                }
            }
        }

Cách 4:

            // First we define the parameter that we are going to use
            // in our OrderBy clause. This is the same as "(contact =>"
            // in the example above.
            var param = Expression.Parameter(typeof(Contact), "contact");

            // Now we'll make our lambda function that returns the
            // "LastName" property by it's name.
            var mySortExpression = Expression.Lambda<Func<Contactobject>>(Expression.Property(param, "LastName"), param);
            using (AdventureWorksEntities context = new AdventureWorksEntities())
            {
                var result = context.Contacts.OrderBy(mySortExpression).ToList();
                foreach (var item in result)
                {
                    Console.WriteLine(item.LastName);
                }
            }

Cập nhật sau

Tags: , , , ,


Categories: linq | linq2entity | visual studio 2010 | c# | vb.net

blog comments powered by Disqus

About me

I'm  currently employed as Software developer at devinition.com and also a Microsoft Certified Technology Specialist (MCTS), Microsoft Certified Professional Developer (MCPD) in Net Framework 2.0 and 3.5: Web Applications and MCTS .NET Framework 3.5, ADO.NET Applications

Powered by BlogEngine.NET 2.5.0.5 - Eco Theme by n3o Web Designers