2. Who did the C# tutorial? What is .NET? What is the .NET framework? What is the CLR? What is OOP? Session 1: Last week
3. Agenda C# 3.0 Language Enhancement C# 4.0 Language Enhancement C# 5 What is LINQ? LINQ Project Goals LINQ Project Architecture Data Binding via LINQ Session 2: Overview
13. Co and Contra variance How are generic types “broken” today? class Animal { } class Sheep : Animal { } void Speak(IEnumerable<Animal> animals) { // Do something with Animals } Not Allowed: IEnumerable<Animal> != IEnumerable<Sheep> var sheep = new List<Sheep>(); Speak(sheep);
17. Auto Implemented Properties Collection Initializers Named parameters Optional parameters Lambdas Can span statements across multiple lines Auto Implemented Properties Collection Initializers (limited) Named parameters Optional parameters Lambdas (limited) Can span statements across multiple lines .NET 3.5
18. Auto Implemented Properties Collection Initializers Named parameters Optional parameters Lambdas Can span statements across multiple lines Auto Implemented Properties Collection Initializers Named parameters Optional parameters Lambdas Can span statements across multiple lines .NET 4
22. First showcased at the American International Toy Fair in New York in 2005 LINQ, a clever bluffing game What is LINQ?
23. LanguageINtegratedQuery Allows you to easily query information about an object LINQ to SQL: An ORM made by Microsoft LINQ to Entities: Another ORM made by Microsoft LINQ to XML: Query over XML ... What is LINQ?
24. Language syntax+ a library of extension methods+ lambda expressions+ anonymous types+ a little magic What is LINQ?
26. LINQ is a natural language extension, part of .NET 3.5 Different data sources are queried with the same syntax. Queries are strongly typed Queries benefit from “Intellisense” Applications becomes less error prone LINQ - How does it solve the problem?
27. Unified programming model for any data type Database Relational Data XML Files Collections & Arrays Introduce more declarative syntax Helps the system find the best execution strategy LINQ Project Goals
28. LINQ Project Architecture C# VB Others... .NET Language Integrated Query (LINQ) LINQ Enabled Data Sources LINQ Enabled ADO.NET LINQ to Objects LINQ to ??? LINQ to XML LINQ to Datasets LINQ to SQL LINQ to Entities <book> <title> <author/> <price /> </title> </book> Objects Database XML
30. stringstrSQL = “SELECT custID FROM Customers“; SqlCommandcmd = new SqlCommand(strSQL, cnn); SqlDataAdapteradAdapter = new SqlDataAdapter(cmd); DataSetdst = new DataSet(); adAdapter.Fill(dst); Standard Data Access Code
31. NorthwindDataContext db = newNorthwindDataContext(); var customers = from c indb.Customers select c; Code by LINQ
34. Stored procedures are easier to work with Relationship editor UI is nicer (more like SQL Server) Performance In a recent benchmark LINQ to SQL performed 5 times faster than LINQ to Entities LINQ 2 SQL
35. More refined ORM than LINQ to SQL Many to Many relationships Richer support for Inheritance Validation Update model from database Mapping Editor LINQ 2 Entities
36. Do you know why you should choose "LINQ to Entities" over "LINQ to SQL"? http://www.ssw.com.au/ssw/Standards/Rules/RulesToBetterLINQ.aspx#WhyLINQtoEntitiesNotSQL What to choose?
41. Thank You! Gateway Court Suite 10 81 - 91 Military Road Neutral Bay, Sydney NSW 2089 AUSTRALIA ABN: 21 069 371 900 Phone: + 61 2 9953 3000 Fax: + 61 2 9953 3105 info@ssw.com.auwww.ssw.com.au
Notas del editor
Click to add notesPeter Gfader Developing Windows and Web applications
Who did the C# tutorial?What is .NET?What is .NET framework?What is the CLR?What is OOP?Classes, Objects, Properties, Events, MethodsEncapsulation, Abstraction, Inheritance, Polymorphism
Ask student questions. Who use c# 3.0 before, what is linq
Some people think that is a kind of backward. But that is not really the case… then….With this feature, the type of the local variable being declared is inferred from the expression used to initialize the variable. This is achieved using the var keyword (familiar to those who work with scripting languages, but actually it is quite different). It allows us to write the following code:The compiler would generate the same IL as if we compiled:Note that there is no un-typed variable reference nor late-binding happening, instead the compiler is inferring and declaring the type of the variable from the right-hand side of the assignment. As a result, the var keyword is generating a strongly typed variable reference.Help developers lazy
Anonyous typesThis feature is simply, creating a complex type on the fly, which helps sometimes when you want a temp variable of complex type, that you'll never use again, so you don't need to write a class for it, so you just tell the compiler to write it for you, as you can see in the slide, you use the varkeyword to refer to the variable, and initailize by specifying the properties of the complex type and in the same time initializing them, so the compiler can also infere the type of the properties so the compiler can generate the class for you.Create a small demo. Live tmpUser.Username …
Lambda Expressions is one of most common features between dynamic and functional languages such as Lisp & Python .. etc.Lambda Expressions is an improvement of the delegate idea, which improved in C# 2.0 as Anonymous Methods, and now in C# 3.0 it is Lambda Expressions.Consider the following code, we declared a delegate called NumericalOperation which refers to a function that accepts two inputs of type int, and returns output of type int, and int first lines in the main, we are using C# 1.x code to use this delegate, so we create an object of the NumericalOperation that refers to the Add function, and then call the function using the delegate.then in the next lines we are using C# 2.0 code to declare the object and in the same time declare the function using the anonymous method style, so we created a function that subtracts two integers, and use it .then in the next lines we are using C# 3.0 code to declare the object and in the same time declaring the function using the lambda expressions code, which is somehow looks weird in the first time, but it is really easy to understandfirst we write the delegate type followed by the object name on the left hand side, then on the right hand side we list all the input parameters that will be used in the expression in a coma list, then the arrow operator => followed by the expression that evaluates the return value.so if you want to write a lambda expression that adds two numbers, so you can say it like thisNumericalOperation op = (x, y) => x + y;delegate intNumericalOperation(int x, int y);internal static void Main(){// C# 1.0 NumericalOperation add = new NumericalOperation(Add);Console.WriteLine("C# 1.0: delegates {0,28}", add(1, 2));//C# 2.0 NumericalOperation sub = delegate(int x, int y){return x - y;};Console.WriteLine("C# 2.0: Anonymous Methods {0,20}", sub(2, 1));//C# 3.0 NumericalOperation mul1 = ( x, y)=> x * y; Console.WriteLine("C# 3.0: Lambda Expressions {0,20}", mul1(4, 5));//Another Approach without the need to write the delegate Func<int, int, int> mul2 = (x, y)=>x*y;Console.WriteLine("C# 3.0: Lambda Expressions {0,20}", mul2(4, 5));}internal static int Add(int x, int y){return x + y;}
„Meta programming is painful”Dynamic code generationEFLINQ2SQLReflection.EmitC# compiler in managed code“Compiler as a service”Neuer C#-Compiler, geschrieben in C# - schonseit 16 Monaten in Arbeit ImplementiertalswiederverwendbaresModul Verwendung des Compilers auseigenenProgrammenherauswirdeinfacher Vorteile Eval Embedding, DSLs, … Meta-programming (etwasunklar) Language Object Model
Show the data access problem!!SQL Server: tables and rowsC#: Objects and propertiesRelational vs. object oriented
As a good start, let's see the problem we've been dealing with for the past decades. Both data manipulation and logic implementation improved in different direction, while the data manipulation were treated declaratively using languages like SQL, on the other hand, logic implementation treated imperatively using Object oriented programming concepts and also standard control flow constructs like conditions & loops.This small problem introduced a bigger problem which is making the application always divided into two different contextThe Data context Relational Databases Structured Documents (XML) Any other data store (Excel sheets, ... etc)The Logic contextand also another problem comes from dealing with different context, which is dealing with every context in a different way, so you can't easily have a join between a relational database table and an object-in-memory collection or XML document, several solutions were provided for this, but they were either too hard or too complexHistory:RecordsetDatasetlinq
The platform provides the basis. 3.5 new technology ---- LINQ
Object-relational mappingLanguage syntax+ a library of extension methods+ lambda expressions+ anonymous types+ a little magic= LINQ
Object-relational mapping
LINQ (Language-Integrated Query) Have more details in the following slides
LINQ is a natural language extension, part of .NET 3.5Different data sources are queried with the same syntax. Queries are strongly typedQueries benefit from intellisenseApplications becomes less error proneLinq is mainly help for developerOptimize
So from understanding the problem, LINQ provides the solution, first it introduce a unified model of dealing with data, which all data can be treated similarly in memory, so you can have something like joining data records coming from a database table with a collection in memory then saving the results in a XML document in the same instruction.Also LINQ is using SQL-like instructions, which are very familiar to developers, and also providing a good level of abstraction using more declarative syntax, which gives the system more space for decisions
LINQ Architecture is very elegant and simple, as shown in the slide it provides queries for both C# 3 & VB9 as a first class citizen, and also it provides an abstraction for different implementations of LINQ like LINQ-To-Objects, LINQ-To-SQL (DLINQ) and LINQ-To-XML (XLINQ).In addition it provides a good extensibility model to implement LINQ on different data stores.LINQ – SQLLINQ - Object
The only difference is select goes last. For the intelence purpose…Interactive with people, before show the LINQ stuff.Write in console application.
String strSQL = "SELECT custID FROM Customers“;SqlCommandcmd = New SqlCommand(strSQL, cnn);SqlDataAdapteradAdapter = New SqlDataAdapter(cmd);DataSetdst = New DataSet();adAdapter.Fill(dst);
NorthwindDataClassesDataContext db = newNorthwindDataClassesDataContext();var customers = from c indb.Customers select c;
Eric’s demo
Dbml – database modelExplain to people the code behind for the layout of that designer.csRun sqlproflier . See LINQ is very smart, can optimize the query for you
# Many to Many relationships * In LINQ to SQL when you model a many to many relationship (e.g. Employees and Territories from Northwind) it involved 3 tables: Employee, EmployeeTerritories and Territory * In LINQ to Entities it only uses the Employee and Territory tables and does not need the associative table EmployeeTerrirories# Richer support for Inheritance * Table per Hierarchy - store all the data from the inherited types into the same table e.g. Employee, Customer classes will store data into the Person table * Table per Type - each type is stored in a separate tables# Validation * This means you can use the designer to make changes and validate it against your schema# Update model from database * This tells you if schema has changed and allows you to update the mapping from the designer. This was a short coming in LINQ to SQL# Mapping EditorAllows you to use the designer to create the mappings - similar to the Java Hibernate editor (eclipse add-in)
Let student download it then show how to use itUse it before presentationChange to C# statementsResult.Count().Dump()How to translate to SQLTutorial