Drani Academy – Interview Question, Search Job, Tuitorials, Cheat Sheet, Project, eBook

ASP.Net Core

Tutorials – ASP.Net Core

 
Chapter 5: Models and Data Access


In the previous chapters, we’ve covered the fundamentals of ASP.NET Core, including controllers, views, routing, and advanced techniques. Now, it’s time to dive into the crucial topic of models and data access. In Chapter 5, we will explore how to define models, interact with databases, and implement data access logic in your ASP.NET Core applications.

5.1 Introduction to Models

Models are an integral part of web applications, serving as the bridge between your application’s business logic and its data. In ASP.NET Core, models represent the structure and behavior of the data you work with, whether it’s data retrieved from a database, user input, or external services.

5.1.1 What Are Models?

In the context of ASP.NET Core, models are classes that define the structure of your application’s data. They encapsulate the data’s properties, relationships, and validation rules. Models serve as the blueprint for your data, enabling you to work with it in a structured and type-safe manner.

Common scenarios for using models include:

  • Representing database tables: Models define the schema of database tables and provide an object-oriented representation of data.

  • Handling form submissions: Models capture user input from web forms, ensuring that data is correctly validated and processed.

  • Data transfer objects (DTOs): Models are used to transfer data between different layers of your application, such as between the controller and the view.

  • Business logic: Models can include methods that implement business rules and logic specific to your application.

5.1.2 Creating Models

To create a model in ASP.NET Core, you define a class with properties that represent the attributes of the data you want to work with. Here’s a simple example of a model representing a “Product”:

public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Description { get; set; }
}

In this example, the Product class defines properties for Id, Name, Price, and Description. Each property corresponds to a piece of data associated with a product.

5.1.3 Data Annotations and Validation

Models can include data annotations to specify validation rules for their properties. Data annotations are attributes applied to model properties that define constraints on the data they can hold.

Here’s an example of using data annotations for validation in a model:

public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Range(0.01, double.MaxValue)]
public decimal Price { get; set; }
public string Description { get; set; }
}

In this updated Product model, the [Required] annotation ensures that the Name property cannot be empty, and the [Range] annotation restricts the Price property to values greater than or equal to 0.01.

5.2 Data Access in ASP.NET Core

Effective data access is a fundamental requirement for most web applications. In this section, we’ll explore different approaches to interact with databases and other data sources in ASP.NET Core.

5.2.1 Entity Framework Core

Entity Framework Core (EF Core) is a popular Object-Relational Mapping (ORM) framework for ASP.NET Core. It simplifies database interactions by allowing you to work with databases using C# classes (models) and LINQ queries. EF Core supports various database providers, including SQL Server, SQLite, MySQL, and more.

Setting up EF Core

To use EF Core in your ASP.NET Core application, follow these steps:

  1. Install EF Core and a database provider package (e.g., Microsoft.EntityFrameworkCore.SqlServer for SQL Server).

  2. Create a DbContext class that represents your database and includes DbSet properties for your models.

public class ApplicationDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
}
  1. Configure the database connection in your application’s appsettings.json file.
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=MyAppDb;Trusted_Connection=True;MultipleActiveResultSets=true"
},
// ...
}
  1. Register the DbContext in your application’s Startup.cs file.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Using EF Core for Data Access

With EF Core set up, you can use it for data access in your controllers or services. Here’s an example of querying products using EF Core:

public class ProductService
{
private readonly ApplicationDbContext _context;
public ProductService(ApplicationDbContext context)
{
_context = context;
}
public List<Product> GetProducts()
{
return _context.Products.ToList();
}
}

In this example, the ProductService class retrieves products from the database using the ApplicationDbContext.

5.2.2 Database Migrations

When working with databases, you often need to make changes to the database schema, such as adding new tables or modifying existing ones. EF Core provides a feature called database migrations to manage these changes.

Creating Migrations

To create a migration, run the following command in the terminal:

dotnet ef migrations add InitialCreate

This command generates a migration file that contains the necessary code to apply the changes to the database.

Applying Migrations

To apply the migrations and update the database schema, run:

dotnet ef database update

This command executes the migration code and brings the database schema in sync with your model classes.

5.2.3 Repository Pattern

The Repository pattern is a design pattern that separates the data access code from the rest of your application. It provides a clear and structured way to interact with data while abstracting the underlying data storage details.

Here’s an example of implementing a repository for the Product model:

public interface IProductRepository
{
List<Product> GetAll();
Product GetById(int id);
void Add(Product product);
void Update(Product product);
void Delete(int id);
}
public class ProductRepository : IProductRepository
{
private readonly ApplicationDbContext _context;
public ProductRepository(ApplicationDbContext context)
{
_context = context;
}
public List<Product> GetAll()
{
return _context.Products.ToList();
}
public Product GetById(int id)
{
return _context.Products.Find(id);
}
public void Add(Product product)
{
_context.Products.Add(product);
_context.SaveChanges();
}
public void Update(Product product)
{
_context.Products.Update(product);
_context.SaveChanges();
}
public void Delete(int id)
{
var product = _context.Products.Find(id);
if (product != null)
{
_context.Products.Remove(product);
_context.SaveChanges();
}
}
}

In this example, the ProductRepository class encapsulates data access operations related to products.

5.2.4 Dependency Injection for Data Access

To use data access components like EF Core or repositories, you should register them in the dependency injection container. This allows you to inject data access dependencies into your controllers or services.

// Startup.cs
services.AddScoped<IProductRepository, ProductRepository>();

With the repository registered, you can inject it into your controller:

public class ProductController : Controller
{
private readonly IProductRepository _productRepository;
public ProductController(IProductRepository productRepository)
{
_productRepository = productRepository;
}
// Controller actions can now use _productRepository for data access.
}

5.3 CRUD Operations with Models

CRUD (Create, Read, Update, Delete) operations are fundamental when working with data in web applications. In this section, we’ll explore how to implement these operations using models and data access.

5.3.1 Creating Records

To create a new record in your database, follow these steps:

  1. Define a model for the data you want to create.

  2. Use data annotations for validation if necessary.

  3. Create a controller action that handles the HTTP POST request for creating a record.

  4. In the action method, validate and process the data, then use data access code to add the record to the database.

5.3.2 Reading Records

Reading records involves retrieving data from the database and displaying it in your application. Common scenarios include displaying a list of records or showing the details of a single record.

To read records, you typically:

  1. Create a controller action to handle the HTTP GET request for reading records.

  2. Use data access code to retrieve the desired data from the database.

  3. Pass the data to a view for rendering.

Here’s an example of a controller action for displaying a list of products:

public class ProductController : Controller
{
private readonly IProductRepository _productRepository;
public ProductController(IProductRepository productRepository)
{
_productRepository = productRepository;
}
public IActionResult Index()
{
var products = _productRepository.GetAll();
return View(products);
}
}

5.3.3 Updating Records

Updating records involves modifying existing data in your database. To update a record:

  1. Create a controller action that handles the HTTP GET request for displaying the data to be updated.

  2. Create another controller action that handles the HTTP POST request for updating the record.

  3. In the update action method, validate and process the data, and use data access code to update the record in the database.

Here’s an example of an update action for a product:

[HttpGet]
public IActionResult Edit(int id)
{
var product = _productRepository.GetById(id);
if (product == null)
{
return NotFound();
}
return View(product);
}
[HttpPost]
public IActionResult Edit(Product product)
{
if (ModelState.IsValid)
{
_productRepository.Update(product);
return RedirectToAction("Index");
}
return View(product);
}

5.3.4 Deleting Records

Deleting records involves removing data from your database. To delete a record:

  1. Create a controller action that handles the HTTP GET request for confirming the deletion.

  2. Create another controller action that handles the HTTP POST request for deleting the record.

  3. In the delete action method, validate and process the data, and use data access code to delete the record from the database.

Here’s an example of a delete action for a product:

[HttpGet]
public IActionResult Delete(int id)
{
var product = _productRepository.GetById(id);
if (product == null)
{
return NotFound();
}
return View(product);
}
[HttpPost, ActionName("Delete")]
public IActionResult DeleteConfirmed(int id)
{
_productRepository.Delete(id);
return RedirectToAction("Index");
}

5.4 Conclusion of Chapter 5

In this chapter, we’ve explored the essential topics of models and data access in ASP.NET Core. Models serve as the foundation for defining your application’s data structure and validation rules. We’ve also discussed various data access techniques, including Entity Framework Core, database migrations, the Repository pattern, and dependency injection.

Understanding how to create, read, update, and delete records is crucial for building robust web applications. In the next chapter, we will delve into authentication and authorization, which are vital for securing your ASP.NET Core applications.

Congratulations! You’ve completed Chapter 5, gaining a deep understanding of models and data access in ASP.NET Core. These concepts are fundamental to building dynamic and data-driven web applications. In the upcoming chapters, we’ll continue our journey by exploring authentication, authorization, and other critical aspects of web development with ASP.NET Core.

Scroll to Top