Download presentation
Presentation is loading. Please wait.
Published byInge Bieber Modified over 6 years ago
1
C# Programming Unit -4 © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
2
Learning Objective Introducing LINQ and XML:
XML A quick introduction. LINQ and C#. Defining and executing a Query. Implicitly typed local variables. Anonymous Types, Extension Methods and Lambda Expressions. Putting LINQ to work. LINQ to SQL Fundamentals of ADO.NET Updating retrieving and deleting data using LINQ to SQL. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
3
XML XML stands for EXtensible Markup Language
XML is a markup language much like HTML. XML was designed to describe data. XML tags are not predefined in XML. You must define your own tags. XML is self describing. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
4
XML HTML XML is not a replacement for HTML.
XML and HTML were designed with different goals XML HTML XML was designed to describe data and to focus on what data is. XML is about describing information. XML allows the author to define his own tags and his own document structure. HTML was designed to display data and to focus on how data looks. HTML is about displaying information The author of HTML documents can only use tags that are defined in the HTML standard. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
5
An example XML document
The first line defines the XML version of the document. In this case the document conforms to the 1.0 specification of XML. <?xmlversion="1.0"?> <note> <to>To,</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> The next line defines the first element of the document (the root element). The next lines defines 4 child elements of the root (to, from, heading, and body): © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
6
Few Characterstics All XML elements must have a closing tag unless like HTML o All XML elements must be properly nested <p>This is a paragraph <p>This is another paragraph <b><i>This text is bold and italic</i></b> <p>This is a paragraph</p> <p>This is another paragraph</p> o All XML documents must have a root tag o XML tags are case <root> <child> <subchild> </subchild> </child> sensitive <Message>This is incorrect</message> </root> © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Del hi-63, by Uttam Singh, Asst. Profe ssor U4.‹N r.›
7
LINQ LINQ stands for Language Integrated Query.
LINQ was added by C# 3.0 It encompasses features that lets you retrieve information from a data source. In order for a source of data to be used by LINQ, it must implement the IEnumerable interface. LINQ gives C# ability to generate queries for any LINQ compatible data source(XML,ADO.NET,SQL). © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
8
LINQ The syntax used for query remains the same –no matter what data source is used. To use the LINQ features you must include the System.Linq namespace LINQ is supported by features like: extension methods. query syntax query methods anonymous expressions. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
9
LINQ Fundamentals At LINQ ‘S core is the query.
Using a query involves two steps: The form of query is created. Query is executed Therefore, Query defines what to retrieve from a data source. Executing a query actually obtains the result. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
10
Creating Query Range variable var posNums = from n in nums
implicitly typed variable Range variable var posNums = from n in nums where n > 0 data source query variable select n; condition keywords © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
11
Implicitly Typed Variable
Implicitly typed variables instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement. The inferred type may be a built-in type, an anonymous type, a user-defined type, or a type defined in the .NET Framework class library. The keyword var declares a variable to be an implicitly typed. i is compiled as an int var i = 5; s is compiled as a string var s = "Hello"; anon is compiled as an anonymous type var anon = new { Name = "Terry", Age = 34 }; © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
12
Executing Query foreach loop
foreach(int i in posNums) Console.Write(i + " "); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
13
First Program using System; using System.Linq; class SimpQuery {
static void Main() int[] nums = { 1, -2, 3, 0, -4, 5 }; // Create a query that obtains only positive numbers. var posNums = from n in nums where n > 0 select n; Console.Write("The positive values in nums: "); // Execute the query and display the results. foreach(int i in posNums) Console.Write(i + " "); Console.WriteLine(); } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
14
A Query can be executed More Than Once
using System; using System.Linq; using System.Collections.Generic; class SimpQuery { static void Main() { int[] nums = { 1, -2, 3, 0, -4, 5 }; // Create a query that obtains only positive numbers. var posNums = from n in nums where n > 0 select n; Console.Write("The positive values in nums: "); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
15
Console.Write("The positive values in nums after change: ");
// Execute the query and display the results. foreach(int i in posNums) Console.Write(i + " "); Console.WriteLine(); // Change nums. Console.WriteLine("\nSetting nums[1] to 99."); nums[1] = 99; Console.Write("The positive values in nums after change: "); // Execute the query a second time. foreach(int i in posNums) Console.Write(i + " "); Console.WriteLine(); } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
16
How the Data Types In a Query relate
var posNums=from int n in nums The statement is interpreted as : IEnumerable<int> posNums = from n in nums © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
17
Filter values using ‘where’
As we know, where is used to filter the data returned by a query. But, where can be used to filter data based on more than one condition i.e: use of multiple where clauses. A where condition can use any valid c# expression that evaluates to a boolean result. Let’s see a sample program….. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
18
Sort results by ‘orderby’
LINQ gives an easy way to produce sorted records by orderby clause. orderby can be used to sort on more than one criteria. Syntax: orderby sort_on direction orderby sort_A direction, sort_B direction,… Sorting can be either ascending or descending. The default direction is ascending. Let’s see a sample program…. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
19
Use of Order by in Linq using System.Linq; class OrderbyDemo { static void Main() { int[] nums = { 10, -19, 4, 7, 2, -5, 0 }; // Create a query that obtains the values in sorted order. var posNums = from n in nums orderby n select n; Console.Write("Values in ascending order: "); // Execute the query and display the results. foreach(int i in posNums) Console.Write(i + " "); } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
20
A Closer look at ‘select’
select detemines what type of elements are obtained by query . select expression; Expression has simply named the range variable It can return a specific portion of the range variable. It may return the result of applying some operation or tranformation. Or, even a new type of object that is constructed from pieces of the information retrieved from the range variable. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
21
Function can be used in Linq
class SelectDemo { static void Main() double[] nums = { -10.0, 16.4, , , -2.2, 25.25, -3.5 } ; // Create a query that returns the square roots of the // positive values in nums. var sqrRoots = from n in nums where n > 0 select Math.Sqrt(n); Console.WriteLine("The square roots of the positive values" + to two decimal places:"); // Execute the query and display the results. foreach(double r in sqrRoots) Console.WriteLine("{0:#.##}", r); } " rounded © Bharati Vidyapee}th’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
22
Use Nested from clause A query can contain more than one from clause. Thus, a query can contain nested from clauses. Use of nested from clause is found when a query needs to obtain data from two different sources. Let’s see a sample program… © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
23
Example :Nested from clause
class ChrPair { public char First; public char Second; public ChrPair(char c1, char c2) { First = c1; Second = c2; } } class MultipleFroms { static void Main() { char[] chrs 1= { 'A', 'B', 'C' }; char[] chrs2 = { 'X', 'Y', 'Z' }; // Notice that the first from iterates over chrs 1 and // the second from iterates over chrs2. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
24
Contd.. var pairs = from ch1 in chrs1 from ch2 in chrs2
select new ChrPair(ch1, ch2); Console.WriteLine("All combinations of ABC with XYZ: "); foreach(var p in pairs) Console.WriteLine("{0} {1}", p.First, p.Second); } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
25
Group results using ‘group’
Group clause enables us to create results that are grouped by keys This makes group an easy and effective way to retrieve data that is organised into sequence of related keys Syntax :group range-variable by key It returns data grouped into sequences, with sequence sharing the key specified by the ‘key’ © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
26
Example :Group by class GroupDemo { static void Main() {
string[] websites = { "hsNameA.com", "hsNameB.net", "hsNameC.net", "hsNameD.com", "hsNameE.org", "hsNameF.org", "hsNameG.tv", "hsNameH.net", "hsNameI.tv" }; // Create a query that groups web sites by top-level domain name. var webAddrs = from addr in websites where addr.LastIndexOf('.') != -1 group addr by addr.Substring(addr.LastIndexOf('.') ); // Execute the query and display the results. foreach(var sites in webAddrs) { Console.WriteLine("Web sites grouped by " + sites.Key); foreach(var site in sites) Console.WriteLine(" " + site); } } } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
27
Use let to create a variable
When we want to retain a value temporarily. Store a value that will be used later on in a where clause. Syntax : let name = expression The type of the name is inferred from the type of expression. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
28
using System; using System.Linq; class LetDemo { static void Main() {
string[] strs = { "alpha", "beta", "gamma" }; // Create a query that obtains the characters in the // strings, returned in sorted order. Notice the use // of a nested from clause. var chrs = from str in strs let chrArray = str.ToCharArray() from ch in chrArray orderby ch select ch; Console.WriteLine("The individual characters in sorted order:"); // Execute the query and display the results. foreach(char c in chrs) Console.Write(c + " "); Console.WriteLine(); } } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
29
Join Two Sequences with join
When working with databases, it is common to want to create a sequence that correlates data from two different data sources. Such an action is easy to accomplish in LINQ through the use of the join clause. The general form of join is shown here (in context from range-varA in data-sourceA join range-varB in data-sourceB with the from): on range-varA.property equals range-varB.property The key to using join is to understand that each data source must contain data in common, and that the data can be compared for equality. Join acts like a filter, allowing only those elements that share a common value to pass through. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
30
class JoinDemo { static void Main() {
Item[] items = { new Item("Pliers", 1424), new Item("Hammer", 7892), new Item("Wrench", 8534), new Item("Saw", 6411) }; InStockStatus[] statusList = { new InStockStatus(1424, true), new InStockStatus(7892, false), new InStockStatus(8534, true), new InStockStatus(6411, true) }; // Create a query that joins Item with InStockStatus to // produce a list of item names and availability. Notice // that a sequence of Temp objects is produced. var inStockList = from item in items join entry in statusList on item.ItemNumber equals entry.ItemNumber select new Temp(item.Name, entry.InStock); Console.WriteLine("Item\tAvailable\n"); // Execute the query and display the results. foreach(Temp t in inStockList) Console.WriteLine("{0}\t{1}", t.Name, t.InStock); } } © Bharati Vidyapeet h’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
31
Anonymous Types C# provides a feature called the anonymous type that directly relates to LINQ. Its primary use is to create an object returned by the select clause. An anonymous type is created through the use of this general form: new { nameA = valueA, nameB = valueB, ... } Here, the names specify identifiers that translate into read- only properties that are initialized by the values. For example, new { Count = 10, Max = 100, Min = 0 } © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
32
Anonymous Types Cont’d
An anonymous type has no name, so we must use an implicitly typed variable to refer to it. This lets the compiler infer the proper type. For example, var myOb = new { Count = 10, Max = 100, Min = 0 } creates a variable called myOb that is assigned a reference to the object created by the anonymous type expression One can simplify the syntax of the anonymous type through the use of a projection initializer. For example, here is another way to code the select clause used by the preceding program: select new { item.Name, entry.InStock }; © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
33
class AnonTypeDemo { static void Main() {
Item[] items = { new Item("Pliers", 1424), new Item("Hammer", 7892), new Item("Wrench", 8534), new Item("Saw", 6411) }; InStockStatus[] statusList = { new InStockStatus(1424, true), new InStockStatus(7892, false), new InStockStatus(8534, true), new InStockStatus(6411, true) }; // Create a query that joins Item with InStockStatus to // produce a list of item names and availability. // Now, an anonymous type is used. var inStockList = from item in items join entry in statusList on item.ItemNumber equals entry.ItemNumber select new { Name = item.Name, InStock = entry.InStock }; Console.WriteLine("Item\tAvailable\n"); // Execute the query and display the results. foreach(var t in inStockList) Console.WriteLine("{0}\t{1}", t.Name, t.InStock); } } © Bharati Vidyapeeth’s Ins titute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
34
Lambda Expression Linq is always associated with Lambda Expressions
Anonymous Methods allows you to write function body inline without the need of writing a delegate function. Lambda Expression consize the concept of Anonymous function writing. delegate intDelType(int i); DelType dd = value) { delegate(int delegate int DelType(int i); DelType d = value => value + 2; return (value +2); }; int i = dd(10); int i = d(10); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
35
DelType d = (value1,value2) => { value1 = value2 = return
// Multiline Function Body delegate int DelType(int i, int j); DelType d = (value1,value2) => { value1 = value2 = return value1 + value2 + 2; value1 + value2; }; © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
36
The Query Methods Query methods is the other way to specify queries in c#. These methods can be called on any enumerable object, such as an array. The query methods are defined by System.Linq.Enumerable and are implemented as extension methods that extend the functionality of IEnumerable<T>. The Enumerable class provides many query methods, but at the core are those that correspond to the query keywords. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
37
The Query Methods Cont’d
Except for Join( ), these query methods take one argument, which is an object of some form of the generic type Func<T, TResult>. This is a built-in delegate type that is declared like this: delegate TResult Func<in T, out TResult>(T arg) Each of these query methods returns an enumerable object. Thus, the result of one can be used to execute a call on another, allowing the methods to be chained together. var posnums = nums.Where(n => n > 0).Select(r => r *10); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
38
using System; using System.Linq; class SimpQuery
{ static void Main() { int[] nums = { 1, -2, 3, 0, -4, 5 }; var posNums = nums.Where(n => n > 0).Select(r=> r*10); Console.Write("The positive values in nums: "); foreach(int i in posNums) Console.Write(i + " "); Console.WriteLine(); }} The output, shown here: The positive values in nums: © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
39
Query Syntax vs. Query Methods
C# has two ways of creating queries: the query syntax and the query methods. The two approaches are closely related than you might assume. The reason is that the query syntax is compiled into calls to the query methods. Thus, when you write something like where x < 10 the compiler translates it into Where (x => x < 10) © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
40
More Query-Related Extension Methods
In addition to the methods that correspond to the query keywords supported by C#, the .NET Framework provides several other query- related extension methods that are often helpful in a query. These query- related methods are defined for IEnumerable<T> by Enumerable. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
41
Extension Methods Cont’d
You can also use the query-related extension methods within a query based on the C# query syntax. For example, this Query uses Average( ) to obtain a sequence that contains only those values that are less than the average of the values in an array. int[] nums = { 1, 2, 4, 8, 6, 9, 10, 3, 6, 7 }; var ltAvg = from n in nums let x = nums.Average() where n < x select n; The output is: The average is 5.6 These values are less than the average: © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
42
Deferred vs Immediate Query Execution
A query defines a set of rules that are not actually executed until a foreach statement executes. This is called deferred execution var chrs = from str in strs let chrArray = tr.ToCharArray() from ch in chrArray orderby ch select ch; foreach(char c in chrs) Console.Write(c + " "); If we use one of the extension methods that produces a non- sequence result, then the query must be executed to obtain that result. In this case, immediate execution takes place, with the query being executed automatically in order to obtain the result. int len = (from n in nums where n > select n). Count(); Console.WriteLine(“\t " + len); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
43
An Introduction to ADO.Net
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
44
What is ADO.Net? The data access classes for the .Net framework
Designed for highly efficient data access Support for XML and disconnected record sets © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
45
Where does ADO sit? VB C# C++ Jscript Common Language Specification …
Visual Studio .NET ASP.Net Windows Forms ADO.Net XML.Net Base Class Library Common Language Runtime (CLR) Windows COM+ Services © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
46
.NET Data Providers Client SQL .NET Data Provider SQL SERVER
OLE DB .NET Data Provider OLE DB Provider Other DB ODBC .NET Data Provider ODBC Driver Other DB © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
47
Data Provider Functionality
Client .Net Data Provider Connection Command Rows DataReader DataSet DataAdapter database © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
48
ADO.Net object model DataAdapter DataSet Errors Collection Command
Fill Update DataAdapter DataSet UpdateCommand SelectCommand DeleteCommand InsertCommand Errors Collection Command Connection Parameters Data Source © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
49
Namespaces System.Data & System.Data.Common
System.Data.SqlClient & System.Data.OleDB System.Data.SqlTypes System.XML & System.XML.Schema © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
50
Using Namespaces C# using using System.Data; System.Data.SqlClient;
SqlDataAdapter sqlAdp= new SqlDataAdapter(); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
51
SQL Namespace Objects using System.Data.SqlClient; SqlConnection
SqlCommand SqlDataReader SqlDataAdapter SqlParameter SqlParameterCollection SqlError SqlErrorCollection SqlException SqlTransaction SqlDbType © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
52
Connecting to SQL using System.Data.SqlClient;
string sConnectionString = "Initial Catalog=Northwind; Data Source=localhost; Integrated Security=SSPI;"; SqlDataAdapter sqlAdp= new SqlDataAdapter(sConnectionString); sqlAdp.Close(); sqlAdp.Dispose(); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
53
Connection Pooling ADO.Net pools connections.
When you close a connection it is released back into a pool. SqlConnection conn = new SqlConnection(); conn.ConnectionString = "Integrated conn.Open(); SqlConnection Security=SSPI;Initial Catalog=northwind"; // Pool A is created. conn = new SqlConnection(); conn.ConnectionString = "Integrated Security=SSPI;Initial Catalog=pubs"; conn.Open(); // Pool B is created because the connection strings differ. SqlConnection conn = new SqlConnection(); conn.ConnectionString = "Integrated Security=SSPI;Initial Catalog=northwind"; conn.Open(); // The connection string matches pool A. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
54
Getting data SqlCommand
ExecuteReader ExecuteNonQuery ExecuteScalar ExecuteXMLReader SqlDataAdapter DataSet © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
55
Using the command object
SqlCommand Multiple constructors New() New(cmdText) New(cmdText, connection) connection, transaction) © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
56
Using the command object
string sSelectQuery = "SELECT FROM Categories ORDER BY CategoryID"; string sConnectionString = "Initial Catalog=Northwind; Data Source=localhost; Integrated Security=SSPI;"; SqlConnection objConnect = new SqlConnection(sConnectString); SqlCommand objCommand = new SqlCommand(sSelectQuery, objConnect); / objCommand.CommandTimeout = 15; objCommand.CommandType = CommandType.Text; objConnect.Open(); SqlDataReader drResults; drResults = objCommand.ExecuteReader() drResults.Close(); objConnect.Dispose(); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
57
Command Methods .ExecuteReader() - Returns DataReader
.ExecuteNonQuery() - Returns # of Rows Affected .ExecuteXMLReader() - Returns XMLReader Object to Read XML documentation .ExecuteScaler() - Returns a Single Value e.g. SQL SUM function. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
58
The DataReader object DataReader objects are highly optimised for fast, forward only enumeration of data from a data command A DataReader is not disconnected Access to data is on a per record basis. Forward only Read only Does support multiple recordsets © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
59
Creating a data reader SqlDataReader sqlReader;
sqlReader = sqlCommand.ExecuteReader(); while (sqlReader.Read()) { // process, sqlReader("field") } sqlReader.Dispose(); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
60
Other Methods GetString(), GetInt() etc.
GetSqlString(), GetSqlInt32() etc. GetValues() IsDBNull() GetSchemaTable() © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
61
DataSets In-memory representation of data contained in a database/XML
Operations are performed on the DataSet, not the data source Can be created programmatically, using a DataAdapter or XML schema and document (or any mixture) Setup SqlConnection Setup a SqlDataAdapter Create a DataSet Call the .Fill() method on the DA © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
62
DataAdapters Pipeline between DataSets and data sources
Geared towards functionality rather than speed Disconnected by design Supports select, insert, delete, update commands and methods. Must always specify a select command All other commands can be generated or specified © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
63
Using the DataAdapter SQLDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = new SqlCommand ("select from authors“, sqlConnection); DataSet sqlDS = new DataSet("authorsTable"); sqlDA.Fill(sqlDS, "authorsTable"); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
64
DataAdapters For speed and efficiency you should set your own InsertCommand, UpdateCommand and DeleteCommand Call GetChanges to seperates the updates, adds and deletes since the last sync. Then sync each type. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
65
DataTables A DataSet contains one or more DataTables.
Fields are held within the DataTable. And in DataRows, DataColumns. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
66
Sets, Tables and Rows DataSet DataTable DataTable DataRow DataRow
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
67
Using DataTables With a DataTable we can Insert, modify and update
Search Apply views Compare Clear Clone and Copy © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
68
Queries to connect with ADO.NET to C#
Namespace used: using System.Data.SqlClient; // create a connection SqlConnection con = new SqlConnection("Initial Catalog = unit4;Data Source=.\SQLEXPRESS ;Integrated Security=True"); // To Select a Value from the table SqlDataAdapter da1 = new SqlDataAdapter("Select * from tblEmployee", con); DataSet ds1 = new DataSet(); da1.Fill(ds1); //show the record in the grid © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor DataGridEmployee.DataSource = ds1.Tables[0]; U4.‹N r.›
69
Insert Update using Ado.net
// To UPDATE A RECORD IN the table SqlCommand cmd = new SqlCommand("Update tblEmployee SET EmployeeName = '" + txtEmployeeName.Text + "',Description = '" + txtDescription.Text + "' WHERE EmployeeID = '" + txtEmpID.Text + "'", con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); // To INSERT A RECORD in the table SqlCommand cmd = new SqlCommand("insert into tblEmployee(EmployeeID,EmployeeName,Description) values('" + txtEmpID.Text + "','" + txtEmployeeName.Text + "','" + txtDescription.Text + "')", con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
70
Exercises : Given a class student with data members as Student ID, First Name, Last Name. Create an array of objects and sort them as per their ID using LINQ. Design a query expression that acts upon each element in the array instance and uses the let keyword and computes let by multiplying the element's value by 100. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
71
LINQ TO SQL © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
72
LINQ To SQL Most programs written today manipulate data in one way or another and often this data is stored in a relational database. Yet there is a huge difference between modern programming languages and databases in how they represent and manipulate information. Modern programming languages define information in the form of objects. Relational databases use rows. Objects have unique identity as each instance is physically different from another. Rows are identified by primary key values. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
73
Solution: LINQ to SQL? LINQ to SQL is an O/RM (Object Relational Mapping) implementation that ships in the .NET Framework "Orcas" release. Allows you to model a relational database using .NET classes. You can then query the database using LINQ, as well as update/insert/delete data from it. Supports transactions, views, and stored procedures. Provides an easy way to integrate data validation and business logic rules into your data model. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
74
LINQ To SQL (Cont..) LINQ to SQL provides a runtime infrastructure for managing relational data as objects without losing the ability to query. Your application is free to manipulate the objects while LINQ to SQL stays in the background tracking your changes automatically. LINQ to SQL is a powerful tool which allows developers to access databases as objects in C# © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
75
Getting Started: We will be creating a Windows Forms Application that allows as to you to query and view records from a particular table using LINQ to SQL classes Creating LINQ to SQL Classes Create a new Windows Forms Application and name it LinqToSqlDemo. (FILE > NEW > PROJECT) In solution explorer right click on lintosqldemo > add new item > linq to sql classes(name it as student.dbml) © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
76
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
77
Create a Connection Create a connection to the studentrecord database:
Choose the Server Explorer from the View menu (Ctrl + W, L). In Express editions of Visual Studio, this tool is called the Database Explorer. Right click on the Data Connections node shown in Figure 3 and choose Add Connection. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
78
Contd.. In the Add Connection dialog select the Browse button and navigate to and select your copy of database1.mdf. Select the OK button. At this stage database1.mdf should appear in your server or database explorer, as shown in Figure on the next slide. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
79
Select the Browse button in the Add Connection dialog and locate your copy of database1.mdf
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
80
The Server Explorer provides a view of the let say Northwind database.
© Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
81
ADDING DATA SOURCE After you create entity classes by using the O/R Designer, you can create an object data source and populate the Data Sources Window with the entity classes. To create an object data source based on LINQ to SQL entity classes On the Build menu, click Build Solution to build your project. On the Data menu, click Show Data Sources. In the Data Sources window, click Add New Data Source. Click Object on the Choose a Data Source Type page and then click Next. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
82
Drag items from the Data Sources window onto a form.
Note: If the Customer class is not available, cancel out of the wizard, build the project, and run the wizard again. Click Finish to create the data source and add the Customer entity class to the Data Sources window. Drag items from the Data Sources window onto a form. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
83
Using the SQL Designer The LINQ to SQL Designer allows you to configure and view the metadata of the tables from the database that you want to query. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
84
SQL Designer(contd…) Drag the Customer table from the Server Explorer onto the SQL designer. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
85
Several things happened as you completed the steps outlined above:
When you added the SQL Designer to your project, a new node in the Solution Explorer called DataClasses1.dbml was added to your project. As shown in Figure, it contains two files, called DataClasses1.dbml.layout and DataClasses1.designer.cs. When you dragged the student table onto the designer, an object relational mapping (ORM) was created between the student table in the database and a studentclass generated by the SQL Designer and placed in DataClasses1.designer.cs. This object is called an entity class and it allows you to access the data and fields of the student tables as if they were an object in your project. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
86
A second class, referred to as a DataContext, was also created
in DataClasses1.designer.cs. This class can be used to automatically connect to the database and to easily access the data and fields in the Customer table. A file called app.config was added to your project. It contains an automatically generated connection string for your database. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
87
Data Context From the developer’s perspective, the architecture for LINQ to SQL is quite simple. Working primarily with a single class called the DataContext, LINQ developers can: 1.Connect to a database 2.Access data 3.Submit changes back to the server © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
88
DataContext After you add a LINQ to SQL file to your project, the empty design surface represents a DataContext ready to be configured. Drag database items from Server Explorer/Database Explorer onto the O/R Designer to create data classes and DataContext methods. The data connection of a DataContext is created based on the first item added to the designer form Server Explorer/Database Explorer. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
89
DataContext Class The DataContext is the main conduit by which you retrieve objects from the database and resubmit changes. You use it in the same way that you would use an ADO.NET Connection. The purpose of the DataContext is to translate your requests for objects into SQL queries made against the database and then assemble objects out of the results. The DataContext enables language-integrated query by implementing the same operator pattern as the standard query operators such as Where and Select. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
90
Code snippet © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
91
To insert ,Delete and view the record
To insert a record Table<studentrecord> stud = dc.GetTable<studentrecord>(); studentrecord s1 = new studentrecord(); s1.student_rollno = Convert.ToInt16(textBox2.Text); s1.student_name = textBox1.Text; stud.InsertOnSubmit(s1); stud.Context.SubmitChanges(); To delete the record var st = (from s in dc.GetTable<studentrecord>() where s.student_rollno == Convert.ToInt16(textBox2.Text) select s).SingleOrDefault(); dc.studentrecords.DeleteOnSubmit(st); dc.SubmitChanges(); To insert the record into Grid view Table<studentrecord> stud = dc.GetTable<studentrecord>(); dataGridView1.DataSource = dc.GetTable<studentrecord>(); © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
92
UPDATE var st = (from s in dc.GetTable<studentrecord>()
where s.student_rollno == Convert.ToInt16(textBox2.Text) select s).SingleOrDefault(); if (st == null) { System.Data.Linq.Table<studentrecord> stud = dc.GetTable<studentrecord>(); studentrecord objStud = new studentrecord(); objStud.student_rollno = Convert.ToInt16(textBox2.Text); objStud.student_name= textBox1.Text; stud.InsertOnSubmit(objStud); dc.SubmitChanges(); } else st.student_rollno = Convert.ToInt16(textBox2.Text); st.student_name= textBox1.Text; © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
93
Short Questions What is XML. Why we use it, explain with a short example? What are the fundamentals of ADO.Net. explain with diagram? How LINQ is beneficial than Stored Procedures? Why select clause comes after from clause in LINQ? What is the benefit of using LINQ on dataset? What is Quantifiers in LINQ? What are extension methods in C#? Explain with example. What is Data Context? Explain with example. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
94
Long Questions What is LINQ . Why we use it .Briefly explain implicitly typed local variables and anonymous type, give a proper example to explain it. Create a windows application which receive a form of student information and provide some operations : Student form should contains: Name , DOB, Address (H.No, Street, city, state) sex, Hobbies, Course. Display the result in Data Grid. Develop the application using LINQ TO SQL. Select some student name and their course on behalf of their age. Update the student record. 3. Delete a particular record 4. Sort the list of student by course. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
95
Long Questions Declare a class ContactInfo, which stores a name, address and phone no. also declare a class Address which contains the fields name, address (all class should have their constructor) then create a LINQ query which use the data source array of ContactInfo and save all the with name to the class address, run the query using foreach and print the name and address. Discuss the benefits of using data through Linq to Sql in compare to ADO.net commands and highlight the important prospects for the c# programmer. © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
96
References Books: Web:
The Complete Reference C# 4.0 ,Tata Mc Graw –Hill Edition, Herbert Schildt [Herbert Schildt] C# 2010 for Programmers, Pearson Education, Paul J. Deitel, Harvey M. Deitel [Paul] Web: 7ec3-498b-9fa aed101f/dotnet%20tutorial%20for%20beginners.pdf © Bharati Vidyapeeth’s Institute of Computer Applications and Management, New Delhi-63, by Uttam Singh, Asst. Professor U4.‹N r.›
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.