3 Data Access With Ado Net And Entity Framework

NET Centric Computing · Unit 3

Data Access with ADO.NET and Entity Framework

Exam-focused notes for Data Access with ADO.NET and Entity Framework (NET Centric Computing, BIT351): what the TU syllabus asks and how it has actually been tested, with 7 solved past questions from this unit.

Data Access with ADO.NET and Entity Framework in short

Most web applications store data in a database. This chapter shows how C# talks to a database using ADO.NET, and how Entity Framework reduces that work by mapping tables to classes.

Data Access with ADO.NET and Entity Framework: notes

ADO.NET architecture

ADO.NET is the set of classes in .NET used to connect to a data source, run commands and read results. It has two main parts.

  1. Data providers do the work of talking to a database. Each provider has its own classes. For SQL Server, they are in Microsoft.Data.SqlClient.
  2. The DataSet is an in-memory copy of data that works without a live connection.

Main provider classes:

  • SqlConnection: opens a connection to the database.
  • SqlCommand: runs an SQL statement or stored procedure.
  • SqlDataReader: reads rows forward only, while connected.
  • SqlDataAdapter: fills a DataSet or DataTable and sends changes back.

ADO.NET works in two modes. In the connected mode, we keep the connection open while we read, using a DataReader. In the disconnected mode, a DataAdapter fetches data into a DataSet, closes the connection, and we work on the copy.

DataReader and DataAdapter classes

PointDataReaderDataAdapter with DataSet
ConnectionNeeds an open connectionOpens, fills, then closes
DirectionForward only, read onlyAny direction, can edit
Speed and memoryFast, low memorySlower, holds data in memory
UseShow a list onceEdit data, bind to controls, work offline

We need the reader when we want quick, read only access to many rows. We need the adapter when we want to keep data in memory, change it and update the database later.

using Microsoft.Data.SqlClient;

using var con = new SqlConnection(connStr);
con.Open();
using var cmd = new SqlCommand("SELECT Id, Name, Price FROM Book", con);
using SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
    Console.WriteLine($"{rd["Id"]} {rd["Name"]} {rd["Price"]}");
}
var da = new SqlDataAdapter("SELECT * FROM Book", connStr);
var ds = new DataSet();
da.Fill(ds, "Book");                         // connection is opened and closed by Fill
DataTable t = ds.Tables["Book"];

What this unit covers

  • ADO.NET architecture
  • DataReader and DataAdapter classes
  • CRUD operations with ADO.NET
  • Object-Relational Mapping concepts
  • Entity Framework advantages
  • Data models and DbContext
  • LINQ queries with Entity Framework

Entity Framework advantages

2081 · 5 marks

List the advantages of Entity framework over ADO.NET. [5]

Show solved answer

Advantages of Entity Framework over ADO.NET

Note: The reference notes did not contain this topic directly. The following answer is based on standard .NET curriculum content appropriate for BSc CSIT.


Entity Framework vs ADO.NET

Entity Framework (EF) is an Object-Relational Mapper (ORM) built on top of ADO.NET that allows developers to work with databases using .NET objects, eliminating most of the manual data-access code.


Advantages of Entity Framework over ADO.NET

1. Automatic Object Mapping

  • In ADO.NET, developers must manually map database columns to object properties using DataReader or DataSet.
  • In EF, database tables are automatically mapped to C# classes (entities), reducing boilerplate code significantly.

2. No Need to Write SQL Queries Manually

  • ADO.NET requires writing raw SQL queries for every database operation.
  • EF uses LINQ (Language Integrated Query) to query the database using C# syntax, making code more readable and type-safe.
// EF Example
var students = context.Students.Where(s => s.Age > 20).ToList();

3. Database Independence

  • ADO.NET code is often tightly coupled to a specific database (SQL Server, MySQL, etc.).
  • EF supports multiple database providers, and switching databases requires minimal code changes.

4. Automatic Change Tracking

  • EF automatically tracks changes made to entity objects and generates the appropriate INSERT, UPDATE, or DELETE SQL statements when SaveChanges() is called.
  • In ADO.NET, developers must write all these SQL statements manually.

5. Reduced Development Time and Code

  • ADO.NET requires writing repetitive code for connection management, command execution, and data reading.
  • EF reduces the amount of code significantly, leading to faster development, easier maintenance, and fewer bugs.

Summary Table

FeatureADO.NETEntity Framework
SQL WritingManualAuto-generated via LINQ
Object MappingManualAutomatic
Change TrackingManualAutomatic
Database IndependenceLowHigh
Development SpeedSlowerFaster

Conclusion: Entity Framework provides a higher level of abstraction over ADO.NET, making database operations simpler, faster to develop, and easier to maintain, though ADO.NET offers more fine-grained control for performance-critical scenarios.

Open this answer on its own page →

CRUD operations with ADO.NET

2081 · 5 marks

Given a table BOOK(ISBN,Name,Author,Price), write a program to update the price of the book to 1000 whose author is John. [5]

Show solved answer

Updating the price of a book from a .NET program

The table is BOOK(ISBN, Name, Author, Price) and the requirement is a single row update: every book whose Author is John must end up with Price set to 1000. The database work itself is one SQL statement.

UPDATE BOOK
SET Price = @price
WHERE Author = @author;

BIT351 is a .NET paper, so the program that carries that statement to the server is written in C#, using either ADO.NET (SqlConnection, SqlCommand, SqlParameter) or Entity Framework Core. Both are acceptable; the ADO.NET version is shown first because it makes the database work explicit.

The ADO.NET version

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

public static class Program
{
    public static void Main()
    {
        const string connectionString =
            "Server=localhost;Database=Library;Trusted_Connection=True;TrustServerCertificate=True;";

        const string sql = "UPDATE BOOK SET Price = @price WHERE Author = @author";

        // using declarations close and dispose the connection and command even on an exception.
        using var connection = new SqlConnection(connectionString);
        using var command = new SqlCommand(sql, connection);

        // The two values travel as typed parameters, never as text pasted into the command.
        command.Parameters.Add("@price", SqlDbType.Decimal).Value = 1000m;
        command.Parameters.Add("@author", SqlDbType.NVarChar, 50).Value = "John";

        try
        {
            connection.Open();

            int rows = command.ExecuteNonQuery();

            if (rows > 0)
            {
                Console.WriteLine(rows + " book(s) by John now cost 1000.");
            }
            else
            {
                Console.WriteLine("No book by John was found, so nothing was updated.");
            }
        }
        catch (SqlException ex)
        {
            Console.WriteLine("Database error: " + ex.Message);
        }
    }
}

ExecuteNonQuery is the method used for INSERT, UPDATE and DELETE: it returns the number of rows the statement affected, which is exactly what is needed to report whether any book by John existed. ExecuteReader would be wrong here because an update returns a row count and not a result set, and ExecuteScalar would be wrong because there is no single value to read back.

The flow of the program is the ordinary ADO.NET sequence.

What happensHow
Describe the server, database and credentialsthe connection string
Hold the parameterised command textSqlCommand
Bind the new price and the author safelySqlParameter objects added to command.Parameters
Open the network connectionconnection.Open()
Run the update and read the row countExecuteNonQuery()
Release the connection back to the poolthe using declarations

Why the values are bound and not pasted in

The command text above is a constant. It is fixed at compile time, and the author name and the price reach the server separately, as data. That matters even in a small exam program: if a value such as the author name were joined onto the command text at run time, a name containing a quote or a trailing OR 1=1 would change the meaning of the statement and update every row in the table. That is SQL injection, and escaping quotes by hand is not a substitute for binding, because it depends on the programmer remembering it at every call site. Parameters remove the problem by construction, and they also let the server reuse the cached execution plan.

The Entity Framework Core version

If the project already has a model, the same update is expressed against objects and EF Core writes the parameterised SQL for you.

using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;

[Table("BOOK")]
public class Book
{
    [Key]
    public string ISBN { get; set; } = "";
    public string Name { get; set; } = "";
    public string Author { get; set; } = "";
    public decimal Price { get; set; }
}

public class LibraryContext : DbContext
{
    public DbSet<Book> Books => Set<Book>();

    protected override void OnConfiguring(DbContextOptionsBuilder options) =>
        options.UseSqlServer(
            "Server=localhost;Database=Library;Trusted_Connection=True;TrustServerCertificate=True;");
}

public static class UpdatePrice
{
    public static void Run()
    {
        using var db = new LibraryContext();

        foreach (Book book in db.Books.Where(b => b.Author == "John"))
        {
            book.Price = 1000m;
        }

        int rows = db.SaveChanges();
        Console.WriteLine(rows + " row(s) updated.");
    }
}

The comparison b.Author == "John" is translated into a parameterised WHERE clause, so this version is as safe as the first one, and SaveChanges wraps the writes in a transaction.

If the result is displayed in an ASP.NET Core page rather than a console, print it through Razor (for example @rows), which HTML encodes the value automatically, so a book name or author taken from the database can never be interpreted as markup in the browser.

Open this answer on its own page →

Data models and DbContext

2080 · 5 marks

Describe about data models and data context. [5]

A data model is a collection of conceptual tools used to describe data, data relationships, data semantics, and consistency constraints. It provides a way to describe the design of a database at the logical and physical levels. - Data is organized in a tree-like structure with parent-child relati...

Open this answer on its own page →

Object-Relational Mapping concepts

2080 · 5 marks

What us the purpose of object relational mapper? Describe. [5]

--- An Object Relational Mapper (ORM) is a programming technique and tool that acts as a bridge between an object-oriented programming language and a relational database. It allows developers to interact with a database using objects and classes instead of writing raw SQL queries. --- The main pu...

Open this answer on its own page →

0 · 5 marks

Describe about ORM. [5]

--- Object-Relational Mapping (ORM) is a programming technique that allows developers to interact with a relational database using an object-oriented paradigm. It creates a "virtual object database" that can be used from within a programming language, eliminating the need to write raw SQL queries...

Open this answer on its own page →

DataReader and DataAdapter classes

2081.1 · 10 marks

Why do we need reader and adapter class? Using ADO.NET, in a relation BOOK (id, author, name, price), delete the books having price less than 500.[10]

  • Relation: BOOK (id, author, name, price) - Task: Delete books where price < 500 - Conceptual question: Need for DataReader and DataAdapter classes No numeric matrices or scheduling data involved. This is a conceptual + programming question. All required information is present. --- ADO.NET suppo...
Open this answer on its own page →

LINQ queries with Entity Framework

0 · 10 marks

Assume a database named 'Library' with relation Book(Id, Name, Price, Author, Pub_Date). Write a program to insert the records of 10 books and retrieve those books which are published in 2022 using Entity Framework.[10]

Database: Library Relation: Book(Id, Name, Price, Author, PubDate) Attributes: - Id - identifier (primary key, integer) - Name - book name (string) - Price - price (numeric) - Author - author name (string) - PubDate - publication date (date) Tasks: 1. Insert records of 10 books. 2. Retrieve books...

Open this answer on its own page →