5 Working With Database

NET Centric Computing · Unit 5 · 6 hrs

Working with Database

Exam-focused notes for Working with Database (NET Centric Computing, CSC378): what the TU syllabus asks and how it has actually been tested, with 7 solved past questions from this unit.

Working with Database in short

This unit covers how an ASP.NET Core application talks to a database: the core ADO.NET classes, the shift to Entity Framework Core as an object-relational mapper, how to add EF Core to an application, and how to perform create, read, update and delete operations against the database.

Working with Database: notes

ADO.NET basics: Connection, Command, Reader and Adapter classes

ADO.NET (Microsoft ActiveX Data Objects) is Microsoft's data access technology for communicating between a .NET application (console, WPF, MVC, Web Forms, and more) and a data source such as SQL Server, Oracle, MySQL, or XML; it provides classes and methods for retrieving and manipulating data. Applications can talk to the database in one of two architectures: a connected architecture, where the application stays connected to the database throughout processing, or a disconnected architecture, where the application connects only when it needs to and works the rest of the time against an in-memory DataSet.

The key classes are the Connection class, which opens and manages a connection to the database along with transactions and connection pooling; the Command class, which stores and executes SQL statements or stored procedures through methods such as ExecuteReader (returns rows, typically from a SELECT), ExecuteNonQuery (runs an INSERT, UPDATE, or DELETE and returns the number of affected rows), ExecuteScalar (returns a single value, such as a count), and ExecuteXmlReader (returns an XML stream); the DataReader class, used together with a Command to read the rows returned by a SELECT; the DataAdapter class, which bridges a DataSet to the database and is especially useful with data-bound controls; and the DataSet class itself, a disconnected, in-memory collection of DataTable objects, together with a Relations collection that can define relationships between them.

AspectDataReaderDataSet
Connection modelConnected: keeps the connection open while readingDisconnected: connection can close once data is fetched
DirectionForward-only, read-onlyCan be navigated and edited freely in memory
ContentsOne result set at a timeMultiple related DataTables at once
Typical useFast streaming reads, filling a reportData-bound UI controls, working offline from the database

What this unit covers

  • ADO.NET basics: Connection, Command, Reader and Adapter classes
  • Entity Framework (EF) Core
  • Object-Relational Mapper (ORM)
  • Adding EF Core to an application: Choosing database provider, data models and data context
  • Querying and Saving data to database: Create, read, update and delete records

ADO.NET basics

2081 · 10 marks

List some advantages of Entity Framework over ADO.NET. Assume a database named 'IOST' with a table FACULTY(Course_Name, CourseID, No_of_Semester, fee). Insert some records using ADO.NET and retrive the fee of records having name CSIT.[10]

Show solved answer

Entity Framework vs ADO.NET and ADO.NET Database Operations


Part 1: Advantages of Entity Framework over ADO.NET

Entity Framework (EF) is an Object/Relational Mapping (O/RM) framework that is an enhancement to ADO.NET giving developers an automated mechanism for accessing and storing data in the database.

#Advantage of Entity FrameworkADO.NET Limitation
1Automated Data Access: EF provides automated mechanism for accessing and storing data; no need to write raw SQL queries manuallyADO.NET requires writing explicit SQL queries for every operation
2O/RM Support: Maps database tables directly to C# classes (domain objects), so developers work with objects instead of tablesADO.NET works at a lower level with DataReaders, DataSets, and manual mapping
3Cross-Platform: EF Core is open-source, lightweight, extensible and cross-platformADO.NET has limited cross-platform support
4Two Development Approaches: Supports Code-First and Database-First approaches giving flexibility in designADO.NET does not support code-first or migration-based schema generation
5Migration Support: In Code-First, EF Core API creates the database and tables using migration based on conventions and configuration in domain classesADO.NET requires manual creation and management of database schema
6Less Boilerplate Code: CRUD operations require significantly fewer lines of code using EFADO.NET requires verbose code (connection, command, reader, etc.) for every operation
7Domain Driven Design (DDD): Code-First approach is useful in DDD, making it suitable for enterprise applicationsADO.NET is not aligned with DDD principles
8Works with .NET Core and .NET 4.5+: EF Core is intended for .NET Core but also supports standard .NET 4.5+ applicationsADO.NET is primarily tied to the traditional .NET framework

Part 2: ADO.NET - Insert Records and Retrieve Fee for CSIT

Database Setup Assumption

  • Database Name: IOST
  • Table: FACULTY(Course_Name, CourseID, No_of_Semester, fee)

Step 1: Create the Table in SQL Server (for reference)

CREATE DATABASE IOST;

USE IOST;

CREATE TABLE FACULTY (
    Course_Name    VARCHAR(100),
    CourseID       INT PRIMARY KEY,
    No_of_Semester INT,
    fee            DECIMAL(10, 2)
);

Step 2: Full ADO.NET C# Code - Insert Records and Retrieve Fee for CSIT

using System;
using System.Data;
using System.Data.SqlClient;

namespace IOSTFacultyApp
{
    class Program
    {
        // Connection string pointing to IOST database
        static string connectionString = 
            "Data Source=.;Initial Catalog=IOST;Integrated Security=True";

        static void Main(string[] args)
        {
            // Step 1: Insert records into FACULTY table
            InsertFaculty("CSIT",   1, 8, 75000.00m);
            InsertFaculty("BCA",    2, 6, 55000.00m);
            InsertFaculty("CSIT",   3, 8, 80000.00m);
            InsertFaculty("BIT",    4, 8, 60000.00m);

            Console.WriteLine("Records inserted successfully.\n");

            // Step 2: Retrieve fee of records where Course_Name = 'CSIT'
            RetrieveCSITFee();

            Console.ReadLine();
        }

        // -------------------------------------------------------
        // Method to INSERT a record into FACULTY table
        // -------------------------------------------------------
        static void InsertFaculty(string courseName, int courseID, 
                                   int noOfSemester, decimal fee)
        {
            // SQL INSERT query using parameterized query to prevent SQL injection
            string insertQuery = @"INSERT INTO FACULTY 
                                   (Course_Name, CourseID, No_of_Semester, fee) 
                                   VALUES 
                                   (@CourseName, @CourseID, @NoOfSemester, @Fee)";

            // Using block ensures connection is closed automatically
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(insertQuery, con))
                {
                    // Add parameters to avoid SQL injection
                    cmd.Parameters.AddWithValue("@CourseName",    courseName);
                    cmd.Parameters.AddWithValue("@CourseID",      courseID);
                    cmd.Parameters.AddWithValue("@NoOfSemester",  noOfSemester);
                    cmd.Parameters.AddWithValue("@Fee",           fee);

                    // Open connection
                    con.Open();

                    // Execute the INSERT command
                    int rowsAffected = cmd.ExecuteNonQuery();

                    Console.WriteLine($"Inserted: {courseName} | Rows Affected: {rowsAffected}");
                }
                // Connection is closed automatically at end of using block
            }
        }

        // -------------------------------------------------------
        // Method to RETRIEVE fee of FACULTY records where 
        // Course_Name = 'CSIT'
        // -------------------------------------------------------
        static void RetrieveCSITFee()
        {
            // SQL SELECT query with WHERE clause to filter CSIT records
            string selectQuery = @"SELECT Course_Name, CourseID, 
                                          No_of_Semester, fee 
                                   FROM FACULTY 
                                   WHERE Course_Name = @CourseName";

            using (SqlConnection con = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(selectQuery, con))
                {
                    // Parameterized filter for Course_Name
                    cmd.Parameters.AddWithValue("@CourseName, "CSIT");

                    con.Open();

                    // Execute the query and read results row by row
                    SqlDataReader reader = cmd.ExecuteReader();

                    Console.WriteLine("Fee details for CSIT:");
                    Console.WriteLine("Course_Name | CourseID | No_of_Semester | Fee");

                    while (reader.Read())
                    {
                        Console.WriteLine(
                            $"{reader["Course_Name"]} | {reader["CourseID"]} | " +
                            $"{reader["No_of_Semester"]} | {reader["fee"]}"
                        );
                    }

                    reader.Close();
                }
                // Connection is closed automatically at end of using block
            }
        }
    }
}

The InsertFaculty method uses a parameterized INSERT with AddWithValue for every field, guarding against SQL injection while adding the four faculty records (two of which are CSIT). The RetrieveCSITFee method then runs a parameterized SELECT ... WHERE Course_Name = @CourseName filtered to "CSIT", opens a SqlDataReader, and loops over reader.Read() to print each matching row's course name, course ID, number of semesters, and fee, giving exactly the fee details for the CSIT records that were inserted.

Open this answer on its own page →

2080 · 5 marks

What is the role of adapter class in ADO.NET? List some features of URL routing. [5]

--- The DataAdapter class in ADO.NET acts as a bridge between a DataSet and a data source (such as a SQL Server database). It is found in the System.Data.SqlClient namespace (e.g., SqlDataAdapter). Role Description ------------------- Fill Retrieves data from the database and populates a DataSet ...

Open this answer on its own page →

2079 · 5 marks

Write an ADO. Net application to read the data from the existing table MOVIE(id, name, genre), where genre is 'comedy'. [5]

  • Table: MOVIE(id, name, genre) - Filter condition: genre = 'comedy' - Task: Read (SELECT) matching rows using ADO.NET This is a programming/theory question, so there are no numeric inputs to extract. All required information is present. --- ADO.NET connects a .NET application to a database using...
Open this answer on its own page →

2076 · 5 marks

What is ADO in ASP?[5]

Show solved answer

What is ADO in ASP?

ADO (ActiveX Data Objects)

ADO is a Microsoft technology used in Active Server Pages (ASP) to connect web applications to databases. It provides a set of COM-based objects that allow developers to access and manipulate data stored in databases (such as MS Access, SQL Server, Oracle, etc.) from within ASP pages.


Key Features of ADO

  • ADO stands for ActiveX Data Objects
  • It is used to connect, retrieve, insert, update, and delete data from a database
  • It works with OLE DB providers to communicate with various databases
  • It is a part of Microsoft's Universal Data Access (UDA) strategy
  • It is simple, fast, and easy to use in classic ASP pages

Main ADO Objects

ObjectDescription
ConnectionEstablishes a connection to the database
RecordsetHolds the data retrieved from the database (like a table of rows)
CommandExecutes SQL queries or stored procedures
ErrorContains details about data access errors

How ADO Works in ASP (Steps)

  1. Create a Connection object to connect to the database
  2. Open the connection using a connection string
  3. Create a Recordset object to hold query results
  4. Execute SQL queries to retrieve or manipulate data
  5. Process the data (display, update, delete)
  6. Close the Recordset and Connection to free resources

Example Code (Classic ASP with ADO)

<%
' Step 1: Create Connection Object
Dim conn, rs, sql
Set conn = Server.CreateObject("ADODB.Connection")

' Step 2: Open Connection
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\mydb.mdb"

' Step 3: Create Recordset Object
Set rs = Server.CreateObject("ADODB.Recordset")

' Step 4: Execute SQL Query
sql = "SELECT * FROM Students"
rs.Open sql, conn

' Step 5: Display Data
Do While Not rs.EOF
    Response.Write rs("StudentName") & " "
    rs.MoveNext
Loop

' Step 6: Close Objects
rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing
%>

Connection String Components

A connection string typically includes:

  • Provider - the OLE DB provider name
  • Data Source - path or server name of the database
  • User ID and Password - credentials (if required)

Advantages of ADO

  • Easy to use and implement in ASP pages
  • Supports multiple database types through OLE DB providers
  • Allows both connected and disconnected data access
  • Supports CRUD operations (Create, Read, Update, Delete)
  • Lightweight and fast for web-based database access

Summary

ADO in ASP is a data access technology that acts as a bridge between an ASP web application and a backend database. It uses objects like Connection, Recordset, and Command to perform database operations efficiently, making it a fundamental component of classic ASP-based web development.

Open this answer on its own page →

Object-Relational Mapper

2081 · 5 marks

What is the task of ORM? Discuss about open redirect attacks. [5]

--- ORM (Object-Relational Mapper) is a programming technique that maps objects in an application to tables in a relational database. Its primary tasks include: - Data Mapping: Maps class properties to database table columns, so developers work with objects instead of raw SQL queries. - CRUD Oper...

Open this answer on its own page →

Querying and Saving data to database

2080 · 10 marks

How do you cache the information of the client and what are its uses? Create a table named BAG(ID, Brand, Price, Date). Perform the following operations using Entity Framework Core. a. Update the Price of those Book to 2000 which are published on 2022. b. Delete the Book which are published in 1981. c. Retrieve the Brand of Book having price greater than 500.[10]

--- Caching is the technique of storing frequently accessed data temporarily in fast-access memory so that subsequent requests can be served without repeatedly querying the database or recomputing results. In web applications (ASP.NET Core), caching client information means keeping a client's dat...

Open this answer on its own page →

Adding EF Core to an application

2078 · 5 marks

Define data model and data context. What does URL routing mean? [5]

--- According to Entity Framework Core, a data model (also called Entity Data Model) is the model that Entity Framework uses to communicate with the underlying database. It is built based on the shape of domain classes, Data Annotations, and Fluent API configurations. The EF model includes three ...

Open this answer on its own page →