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.
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 answerHide 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 Framework | ADO.NET Limitation |
|---|---|---|
| 1 | Automated Data Access: EF provides automated mechanism for accessing and storing data; no need to write raw SQL queries manually | ADO.NET requires writing explicit SQL queries for every operation |
| 2 | O/RM Support: Maps database tables directly to C# classes (domain objects), so developers work with objects instead of tables | ADO.NET works at a lower level with DataReaders, DataSets, and manual mapping |
| 3 | Cross-Platform: EF Core is open-source, lightweight, extensible and cross-platform | ADO.NET has limited cross-platform support |
| 4 | Two Development Approaches: Supports Code-First and Database-First approaches giving flexibility in design | ADO.NET does not support code-first or migration-based schema generation |
| 5 | Migration Support: In Code-First, EF Core API creates the database and tables using migration based on conventions and configuration in domain classes | ADO.NET requires manual creation and management of database schema |
| 6 | Less Boilerplate Code: CRUD operations require significantly fewer lines of code using EF | ADO.NET requires verbose code (connection, command, reader, etc.) for every operation |
| 7 | Domain Driven Design (DDD): Code-First approach is useful in DDD, making it suitable for enterprise applications | ADO.NET is not aligned with DDD principles |
| 8 | Works with .NET Core and .NET 4.5+: EF Core is intended for .NET Core but also supports standard .NET 4.5+ applications | ADO.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.
2080 · 5 marks
What is the role of adapter class in ADO.NET? List some features of URL routing. [5]
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]
2076 · 5 marks
What is ADO in ASP?[5]
Show solved answerHide 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
| Object | Description |
|---|---|
| Connection | Establishes a connection to the database |
| Recordset | Holds the data retrieved from the database (like a table of rows) |
| Command | Executes SQL queries or stored procedures |
| Error | Contains details about data access errors |
How ADO Works in ASP (Steps)
- Create a Connection object to connect to the database
- Open the connection using a connection string
- Create a Recordset object to hold query results
- Execute SQL queries to retrieve or manipulate data
- Process the data (display, update, delete)
- 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.
Object-Relational Mapper
2081 · 5 marks
What is the task of ORM? Discuss about open redirect attacks. [5]
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]
Adding EF Core to an application
2078 · 5 marks
Define data model and data context. What does URL routing mean? [5]
Make Unit 5 stick
Practice CSC378 with flashcards & quizzes