.NET Data Access APIs
This section provides comprehensive documentation on the various APIs and technologies available in the .NET ecosystem for interacting with data sources.
Overview
The .NET platform offers a rich set of libraries and frameworks designed to facilitate efficient and secure data access. Whether you are working with relational databases, NoSQL stores, flat files, or web services, .NET provides powerful tools to manage your data.
Key Data Access Technologies
Below are the primary technologies and namespaces you'll encounter when working with data in .NET:
ADO.NET
ADO.NET is the foundational data access technology in .NET, providing a set of classes for connecting to data sources, executing commands, and retrieving results. It offers a disconnected data access model, allowing you to fetch data and work with it independently of the database connection.
- Connections (
System.Data.Common
,System.Data.SqlClient
, etc.) - Commands (
DbCommand
) - Data Readers (
DbDataReader
) - Datasets and DataTables (
DataSet
,DataTable
) - Transactions
Entity Framework Core (EF Core)
Entity Framework Core is a modern, open-source, cross-platform Object-Relational Mapper (ORM) for .NET. It enables developers to work with databases using .NET objects and LINQ queries, abstracting away much of the underlying SQL.
Other Data Access Patterns
Beyond ADO.NET and EF Core, .NET supports various other approaches for data interaction:
- Dapper: A popular micro-ORM that offers high performance for mapping query results to objects.
- NoSQL Data Access: Libraries for interacting with NoSQL databases like MongoDB, Cosmos DB, Redis, etc.
- Web Service Clients: Using
HttpClient
and related classes to consume RESTful APIs. - File I/O: Reading from and writing to various file formats (JSON, XML, CSV, etc.) using classes in
System.IO
andSystem.Text.Json
.
Important: Always prioritize secure data access practices, including parameterized queries to prevent SQL injection and proper handling of sensitive information.
Example: Basic ADO.NET Query
Here's a simple example demonstrating how to fetch data using ADO.NET:
using System;
using System.Data;
using System.Data.SqlClient;
public class DataAccessExample
{
private const string ConnectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
public static void GetProducts()
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
string query = "SELECT ProductID, ProductName, UnitPrice FROM Products";
SqlCommand command = new SqlCommand(query, connection);
try
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int productId = reader.GetInt32(0);
string productName = reader.GetString(1);
decimal unitPrice = reader.GetDecimal(2);
Console.WriteLine($"ID: {productId}, Name: {productName}, Price: {unitPrice:C}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
}