MSDN Documentation

.NET Framework and .NET Core

Introduction to Data Access in .NET

Data access is a fundamental aspect of application development, enabling your .NET applications to interact with various data sources. .NET provides a rich set of technologies and libraries to facilitate efficient, secure, and robust data operations.

This section covers the primary mechanisms and best practices for accessing data from your .NET applications, including relational databases, NoSQL databases, and other storage solutions.

Key Technologies

  • ADO.NET: The foundational data access technology in .NET, offering a set of classes for connecting to data sources, executing commands, and retrieving results.
  • Entity Framework Core (EF Core): A modern, cross-platform Object-Relational Mapper (ORM) that enables .NET developers to work with databases using .NET objects, abstracting away much of the underlying SQL.
  • Data Providers: Specific libraries designed to interact with particular database systems (e.g., SQL Server, PostgreSQL, MySQL, SQLite).
  • Data Binding: The process of connecting UI elements to data sources to display and manipulate data.
  • Serialization: Converting data structures and object states into a format that can be stored or transmitted and reconstructed later.

ADO.NET Deep Dive

ADO.NET provides a collection of classes that expose data access services to the .NET programmer. It consists of components that allow applications to connect to a data source, execute commands, retrieve data, and process results. Key components include:

  • Connection objects: Establish a connection to a data source.
  • Command objects: Represent Transact-SQL statements or stored procedures to be executed against the data source.
  • DataReader objects: Provide a forward-only, read-only stream of data from the data source. Efficient for retrieving large amounts of data.
  • DataSet and DataTable objects: In-memory cache of data that can be used independently of the data source. Useful for disconnected data scenarios.

Example of using ADO.NET:


using System.Data.SqlClient;

// ...

string connectionString = "Your_Connection_String_Here";
string query = "SELECT CustomerID, CompanyName FROM Customers WHERE City = @City";

using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(query, connection);
    command.Parameters.AddWithValue("@City", "London");

    connection.Open();
    SqlDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        Console.WriteLine($"ID: {reader["CustomerID"]}, Name: {reader["CompanyName"]}");
    }
    reader.Close();
}
                

Entity Framework Core (EF Core)

EF Core simplifies data access by allowing you to query and save data as objects, eliminating the need for most of the data-access code you’d typically write. It supports LINQ (Language Integrated Query) for querying databases.

EF Core offers two main approaches:

  • Code-First: Define your .NET model classes first, and EF Core creates the database schema based on them.
  • Database-First: Scaffolds .NET model classes from an existing database schema.
  • Model-First: Define your model in a visual designer and generate code and database schema.

Basic EF Core query:


using (var context = new BloggingContext())
{
    var blogs = context.Blogs
                       .Where(b => b.Url.Contains("example.com"))
                       .OrderBy(b => b.Rating);

    foreach (var blog in blogs)
    {
        Console.WriteLine($"Blog: {blog.Url}");
    }
}
                

Understanding Data Providers

Different databases require specific connectors, known as providers. For ADO.NET, these are typically found in namespaces like System.Data.SqlClient for SQL Server, System.Data.OleDb for OLE DB providers, etc. For EF Core, providers are installed via NuGet packages (e.g., Microsoft.EntityFrameworkCore.SqlServer).

Querying Data

Queries can be executed using raw SQL strings with ADO.NET or using LINQ with ORMs like EF Core. LINQ provides compile-time type checking and IntelliSense, leading to more robust and maintainable code.

Managing Transactions

Transactions are crucial for maintaining data integrity, especially when performing multiple related operations. ADO.NET provides DbTransaction objects for explicit transaction management. EF Core also supports transactions through its DbContext.

Data Binding in UI Frameworks

When building user interfaces with WPF, WinForms, or Blazor, data binding allows you to synchronize data from your data sources with UI controls, simplifying the process of displaying and updating information.

Data Serialization

Serialization is used to convert objects into a stream of bytes (or other formats like JSON or XML) that can be saved to a file, transmitted over a network, or stored in a database. Common serializers include System.Text.Json (modern and recommended) and Newtonsoft.Json (popular third-party library).