Page 88 - CSharp/C#
P. 88

Or if you were just performing a simple update and didn't require a reader, the same basic concept
        would apply :


         using(var connection = new SqlConnection("{your-connection-string}"))
         {
              var query = "UPDATE YourTable SET Property = Value WHERE Foo = @foo";
              using(var command = new SqlCommand(query,connection))
              {
                   connection.Open();

                   // Add parameters here

                   // Perform your update
                   command.ExecuteNonQuery();
              }
         }


        You can even program against a set of common interfaces and not have to worry about the
        provider specific classes. The core interfaces provided by ADO.NET are:


            •  IDbConnection - for managing database connections
            •  IDbCommand - for running SQL commands
            •  IDbTransaction - for managing transactions
            •  IDataReader - for reading data returned by a command
            •  IDataAdapter - for channeling data to and from datasets


         var connectionString = "{your-connection-string}";
         var providerName = "{System.Data.SqlClient}"; //for Oracle use
         "Oracle.ManagedDataAccess.Client"
         //most likely you will get the above two from ConnectionStringSettings object

         var factory = DbProviderFactories.GetFactory(providerName);

         using(var connection = new factory.CreateConnection()) {
             connection.ConnectionString = connectionString;
             connection.Open();

             using(var command = new connection.CreateCommand()) {
                 command.CommandText = "{sql-query}";    //this needs to be tailored for each database
         system

                 using(var reader = command.ExecuteReader()) {
                     while(reader.Read()) {
                         ...
                     }
                 }
             }
         }



        Entity Framework Connections


        Entity Framework exposes abstraction classes that are used to interact with underlying databases
        in the form of classes like DbContext. These contexts generally consist of DbSet<T> properties that
        expose the available collections that can be queried :




        https://riptutorial.com/                                                                               34
   83   84   85   86   87   88   89   90   91   92   93