ASP .NET Tutorial: Code First Approach šŸš€

beginner
11 min

ASP .NET Tutorial: Code First Approach šŸš€

Welcome to the CodeYourCraft ASP .NET Tutorial! In this lesson, we'll dive into the Code First Approach, a powerful strategy that simplifies database creation and development in ASP .NET applications. Let's get started! šŸŽÆ

Understanding Code First Approach šŸ“

In a Code First Approach, you write your models (representing database tables) in code first, and Entity Framework (EF) generates the corresponding database schema automatically. This approach offers several advantages:

  • Efficiency: Avoid writing complex SQL scripts for database creation.
  • Flexibility: Easily modify your models and let Entity Framework adjust the database schema for you.
  • Productivity: Focus on the business logic instead of database schema management.

Setting Up Your Development Environment šŸ’”

Before we dive into the Code First Approach, let's ensure your development environment is ready:

  1. Install Visual Studio (Community Edition)
  2. Install .NET Core SDK (Latest version)
  3. Create a new ASP .NET Core Web Application (select "Empty" template)

Creating Models with Code First Approach šŸ“

Now that our environment is set up, let's create our first model:

csharp
using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } // Navigation property for related data public ICollection<Order> Orders { get; set; } }

šŸ“ Note: Our Product model has properties for Id, Name, and Price. We also defined a navigation property Orders to represent related data (orders that contain this product).

Configuring the Database Context šŸ’”

Now, let's configure our database context:

csharp
public class ApplicationDbContext : DbContext { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Product> Products { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { // Configure database schema } }

šŸ“ Note: We defined a DbSet for our Product model in the ApplicationDbContext. The OnModelCreating method is where we configure the database schema.

Configuring the Database Schema šŸ’”

Finally, let's configure the database schema for our Product model:

csharp
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Product>() .HasKey(p => p.Id); modelBuilder.Entity<Product>() .Property(p => p.Name) .IsRequired() .HasMaxLength(100); modelBuilder.Entity<Product>() .Property(p => p.Price) .HasColumnType("decimal(18, 2)"); }

šŸ“ Note: We configured the Id as the primary key, defined that the Name should be required and have a maximum length of 100 characters, and set the Price's data type to decimal(18, 2).

Running Migrations and Creating the Database šŸ’”

Now that our models and database context are set up, we can create the database using migrations:

  1. Add the following package to your project's .csproj file:
xml
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.0" />
  1. Add the following command to your project's dotnet.json file:
json
{ "runtimes": { ... "Microsoft.AspNetCore.App": { "version": "5.0.0" } } }
  1. Run the following command to create the initial migration:
dotnet ef migrations add InitialCreate
  1. Apply the migration and create the database:
dotnet ef database update

Adding Real-World Data šŸ’”

Now that our database is created, let's add some real-world data:

csharp
using Microsoft.EntityFrameworkCore; var context = new ApplicationDbContext(); // Insert sample data var product1 = new Product { Name = "Laptop", Price = 1000M }; var product2 = new Product { Name = "Smartphone", Price = 500M }; context.Products.AddRange(product1, product2); context.SaveChanges();

šŸ“ Note: We created an instance of ApplicationDbContext, added some sample data, and saved the changes to the database.

Wrapping Up āœ…

Congratulations! You've completed the Code First Approach lesson. You now have a solid foundation for working with databases using the Code First Approach in ASP .NET.

Quiz šŸ’”

Quick Quiz
Question 1 of 1

What is the primary purpose of the OnModelCreating method in the ApplicationDbContext class?