Download pptx - LINQ presentation

Transcript
Page 1: LINQ presentation

Trần Chí KhangMicrosoft Student PartnersEmail: [email protected]

LINQ

Page 2: LINQ presentation

o Khái niệmo Phân loại• LINQ to Object• LINQ to XML• LINQ to Dataset• LINQ to SQL

o ADO.NETo ADO.NET EntityFrameworko LINQ vs ADO.NETo DEMO

NỘI DUNG

Page 3: LINQ presentation

Dữ liệu có thể được lưu trữ ở nhiều nơi• Database(SQL Server,Oracle …)• XML files• File  (Access, Excel …)

Cách giao tiếp ?

Page 4: LINQ presentation

KHÁI NIỆM LINQ

Là ngôn ngữ truy vấn được tích hợp vào ngôn ngữ lập trình (VB, C#, …).

Đưa ra khả năng lập trình mới trong .NET-Giải pháp lập trình hợp nhất

Page 5: LINQ presentation

from customer in Customerswhere customer.Name == "Foysal"select customer

Page 6: LINQ presentation

LINQ TO OBJECTSử dụng LINQ để truy vấn tập hợp các đối tượng

dưới dạng IEnumerable hoặc IEnumerable<T>

List<Students> MaleStudents = new List<Students>();Foreach(Students student in Students){ if(student.sex == “male”) { MaleStudents.Add(student); }}

IEnumerable <Students> MaleStudents =from student in Studentswhere student.sex==“male”select student;

Without LINQ With LINQ

Page 7: LINQ presentation

LINQ TO XML XmlDocument doc = new XmlDocument();XmlElement books = doc.CreateElement("books");XmlElement author = doc.CreateElement("author");author.InnerText = "Fabrice Marguerie";XmlElement price= doc.CreateElement(“price");author2.InnerText = “80”;XmlElement publishyear = doc.CreateElement(“publishyear");author3.InnerText = “2008";XmlElement title = doc.CreateElement("title");title.InnerText = “ABC";XmlElement book = doc.CreateElement("book");book.AppendChild(author1);book.AppendChild(author2);book.AppendChild(author3);book.AppendChild(title);books.AppendChild(book);doc.AppendChild(books);

XDocument xmlbooks = new XDocument( new XDeclaration("1.0", "UTF-16", "yes"), new XElement("books", new XElement("book", new XAttribute("id","B01"), new XElement("author", "Fabrice Marguerie"), new XElement("price", 80), new XElement("publishyear", 2008), new XElement("title", "ABC"))));

<?xml version="1.0" encoding="utf-8" ?>

<books>

<book id = “B01”>

<title>ABC</title>

<author>Fabrice Marguerie </author>

<price>80</price>

<pulishyear>2008</pulishyear>

</book>

</books>

Page 8: LINQ presentation

LINQ TO XML Cung cấp 1 công cụ mạnh mẽ trong việc

truy vấn XML

var books = from b in xmlbooks.Elements("book") where (String)b.Element("price") == 80

select new { title = (String)b.Element("tilte"), author = (String)b.Element("author") };

foreach (var book in books) { Console.WriteLine(book); }

Page 9: LINQ presentation

LINQ TO DATASET

DATASET ?

LINQ to DataSet giúp truy vấn đối tượng Dataset dễ dàng và nhanh chóng

var cus = from c in customersDataset.Tables["Customers"].AsEnumerable()

select c["CustomerID"];

foreach (var c in cus)

{

Console.WriteLine("{0}", c);

}

Page 10: LINQ presentation

LINQ TO SQLLINQ to SQL là một phiên bản Object-Relational

Mapping (ORM).

Database

Table

View

Column

Relationship

Stored Procedure

DataContext

Class

Class

Field / Property

Field / Property

Method

Page 11: LINQ presentation

Lớp DataContext

• Là một class kết nối đến CSDL ở SQL Server

• Chuyển câu truy vấn thành câu lệnh SQL

•Đảm nhận việc tương tác với CSDL

• Thay đổi CSDLthông qua phương thức

SubmitChanges().

Page 12: LINQ presentation

LINQ TO SQL

NorthwindDataContext db = new NorthwindDataContext();

var query = from c in db.Customers where c.City == "London"

select new { Name = c.ContactName, Country = c.Country, City = c.City };

Page 13: LINQ presentation

CẤU TRÚC LINQ TO SQL

from c in db.Customerswhere c.City == "London"select new {Name, Phone};

SELECT CompanyName, PhoneFROM CustomersWHERE City == 'London'

db.Customers.InsertOnSubmit(c1);c2.City = “Seattle";db.Customers.DeleteOnSubmit(c3);

INSERT INTO Customers…UPDATE Customers…DELETE FROM Customers…

Page 14: LINQ presentation

Transaction Transaction là một dịch vụ nhằm đảm bảo rằng một

tập các thao tác độc lập sẽ được thực thi như một đơn

vị duy nhất NorthwindDataContext db = new NorthwindDataContext(); using (TransactionScope ts = new TransactionScope()) { try { Product prod1 = db.Products.First(p => p.ProductID == 4); Product prod2 = db.Products.First(p => p.ProductID == 5);

prod1.UnitsInStock -= 3;prod2.UnitsInStock -= 5;db.SubmitChanges();ts.Complete();

} catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine("Error submitting changes,all changes rolled back."); } }

Page 15: LINQ presentation

Deferred Execution var q = from d in db.Doctors

where d.City == "London"

select d;

if (orderByLocation)

{

q = from d in q

orderby d.Country, d.City

select d;

}

else if (orderByName)

{

q = from d in q

orderby d.DoctorName

select d;

}

foreach (Doctor d in q) Console.WriteLine(d.DoctorName);

Page 16: LINQ presentation

ADO.NET

Page 17: LINQ presentation

Truy cập CSDL với ADO.NET

SqlConnection connection = new SqlConnection(…);connection.Open();SqlCommand cmd = new SqlCommand( “Select Name, Phone From Customers Where City = @city “);

cmd.Parameters.AddWithValue(“@city”, ”London”);Datareader dr = connection.Execute(cmd);While (dr.Read()){ string name = dr.GetString(0); string phone = dr.GetString(1); DateTime date = dr.GetDateTime(2);}dr.Close();Connection.Close();

Chuỗi truy vấn

Xác định kiểu dữ liệu kết quả

Page 18: LINQ presentation

ADO.NET ENTITY FRAMEWORK

Page 19: LINQ presentation

Entity Data Model (EDM)

Page 20: LINQ presentation

LINQ vs ADO.NET

LINQ là tập mở rộng cho phép viết các câu truy vấn ngay trong các ngôn ngữ lập trình.

ADO.NET là công nghệ cho phép các ứng dụng có thể kết nối và làm việc với các loại CSDL khác nhauLINQ không phải là một công nghệ được tạo ra để thay thế

ADO.NET

Page 21: LINQ presentation

DEMO

Page 22: LINQ presentation

Cảm ơn !


Recommended