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.
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 answerHide 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
DataReaderorDataSet. - 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, orDELETESQL statements whenSaveChanges()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
| Feature | ADO.NET | Entity Framework |
|---|---|---|
| SQL Writing | Manual | Auto-generated via LINQ |
| Object Mapping | Manual | Automatic |
| Change Tracking | Manual | Automatic |
| Database Independence | Low | High |
| Development Speed | Slower | Faster |
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.
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 answerHide 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 happens | How |
|---|---|
| Describe the server, database and credentials | the connection string |
| Hold the parameterised command text | SqlCommand |
| Bind the new price and the author safely | SqlParameter objects added to command.Parameters |
| Open the network connection | connection.Open() |
| Run the update and read the row count | ExecuteNonQuery() |
| Release the connection back to the pool | the 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.
Data models and DbContext
Object-Relational Mapping concepts
2080 · 5 marks
What us the purpose of object relational mapper? Describe. [5]
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]
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]
Make Unit 3 stick
Practice BIT351 with flashcards & quizzes