DEV Community

Cover image for Learning in Reverse: How I Would Learn ASP. Net Core and Entity Framework If I Could Go Back In Time
Cindy Nguyen
Cindy Nguyen

Posted on

Learning in Reverse: How I Would Learn ASP. Net Core and Entity Framework If I Could Go Back In Time

My journey to mastering ASP.NET Core and Entity Framework has been both rewarding and challenging. When I first encountered this powerful C# framework, I felt overwhelmed and uncertain about where to start. But through persistence, trial, and error, I’ve made significant progress.
Looking back, I realize there are several key concepts I wish I had focused on from the beginning. While I can’t rewrite my own learning process (and avoid the risk of a time paradox), I hope to share what I've learned with others who are starting on the same path. My goal is to help you navigate the learning curve more smoothly and make your journey as rewarding as mine has been.

First of all, why learn ASP.NET CORE and Entity Framework? (And what is the difference?)

ASP.NET Core is a cross-platform, high-performance framework for building modern full-stack web applications. Its modular architecture and built-in dependency injection make it appealing for C# developers looking to build scalable and maintainable projects through the lenses of Object object-oriented programming.

Entity Framework(EF) is an Object Relation Mapper (ORM) that essentially acts as a bridge between the classes (which are objects) in your code and the tables in the database. You can think of tables being represented by your classes, the properties of your class as the columns, and instances as rows. This framework also abstracts much of the SQL querying and uses LINQ more commonly to obtain data.

EF and ASP.NET Core are not the same. They are distinct components but are often used in conjunction to build full-stack applications. This idea confused me when I first started learning how to create a functioning backend in C#.

The Importance of Learning How to Learn

Learning ASP.NET Core as an autodidact can be daunting, especially without the support of mentors. Success lies in finding the "sweet spot"—tasks just beyond your current abilities, challenging yet achievable with the right resources. Everyone's sweet spot is different, but focusing on concepts that push you without overwhelming you is key to mastering ASP.NET Core.

1. Understand the General Project Setup and Folder Structure for ASP.NET Core

ASP.NET Core applications start with a large but well-defined folder structure to help organize and maintain code as a project can grow; however, at first glance, it can look overwhelming. Understanding this folder structure will be essential to working and learning ASP.NET Core. I’ll give a quick breakdown of this structure along with some short summaries.

The general structure will look something like this:

Controllers/: Contains classes that handle HTTP requests and responses. You’ll write your logic for your RESTful API’s here.

Models/: Defines your data structures, often used with EF to represent database entities. This is where you’ll create your classes that will be mapped into the database.

Views/: Stores Razor Pages or HTML templates with embedded C#.

Data/: Includes DbContext and EF-related files for managing database interactions.

Program.cs: Contains the entry point of your app and you’re expected to configure your services, tools that can be used/”injected” throughout your app,(EF, dependency injections), and request pipeline (middleware) for the application

2. Start with the Fundamentals: Learn C# and the Basics of ASP.NET Core

ASP.NET Core is built on C#, and understanding the language is the first step toward mastering the framework. If you’re also a JavaScript developer looking to learn to C# and would like a guide, I’ve made a blog post to help you transition to C# as a Javascript developer. Check it out! You’ll need it to make it this far. Once you’re comfortable with C#, focus on the foundational components of ASP.NET Core:

MVC (Model-View-Controller): Understanding the MVC pattern is essential, as it is the foundation of most web applications in ASP.NET Core. It is an architectural design that will help you plan out projects if you have a solid understanding of it.
In the MVC pattern:

Model: Represents the data and the logic of the application (e.g., database entities).

View: Represents the user interface (UI) hence the name “view”, typically using Razor Pages (HTML templates with embedded C#).

Controller: Handles user input, interacts with the model, and selects the appropriate view.

Dependency Injection: This is a key feature of ASP.NET Core and an important concept in object-oriented design. Dependency Injection is a way to give a class the tools (dependencies) it needs without the class creating them. Instead, these dependencies are provided from the outside. This makes the code more flexible and easier to manage. Learning how DI works in ASP.NET Core will help you structure your applications in an organized manner. A good way to understand dependency injection is by comparing it to Polymorphism. While polymorphism allows a class to change its behavior based on the type of object it interacts with (depending on the context), dependency injection provides those behaviors (or dependencies) from an external source, instead of having the class create or manage them internally.

Polymorphism Example
The Vehicle class does not store or manage the dependency (IWheel) itself. Instead, it interacts with the provided IWheel only when a method (e.g., TestWheel) is called. The caller determines which implementation of IWheel is passed during each method invocation.

// Define a common interface for wheels
public interface IWheel
{
    void Rotate();
}

// Implement different types of wheels
public class CarWheel : IWheel
{
    public void Rotate()
    {
        Console.WriteLine("Car wheel is rotating.");
    }
}

public class BikeWheel : IWheel
{
    public void Rotate()
    {
        Console.WriteLine("Bike wheel is rotating.");
    }
}

// The Vehicle class uses polymorphism to interact with different wheel types
public class Vehicle
{
    public void TestWheel(IWheel wheel)
    {
        wheel.Rotate();
    }
}

// Example usage
class Program
{
    static void Main()
    {
        Vehicle vehicle = new Vehicle();

        // Use a car wheel
        IWheel carWheel = new CarWheel();
        vehicle.TestWheel(carWheel);  // Output: "Car wheel is rotating."

        // Use a bike wheel
        IWheel bikeWheel = new BikeWheel();
        vehicle.TestWheel(bikeWheel);  // Output: "Bike wheel is rotating."
    }
}

Enter fullscreen mode Exit fullscreen mode

Dependency Injection
The Vehicle class receives and stores the dependency (IWheel) through its constructor. This establishes a persistent relationship between Vehicle and the provided IWheel implementation, which is then used in its methods.

// Define a common interface for wheels
public interface IWheel
{
    void Rotate();
}

// Implement different types of wheels
public class CarWheel : IWheel
{
    public void Rotate()
    {
        Console.WriteLine("Car wheel is rotating.");
    }
}

// The Vehicle class depends on IWheel and receives it via DI
public class Vehicle
{
    private readonly IWheel _wheel;

    // Constructor injection
    public Vehicle(IWheel wheel)
    {
        _wheel = wheel;
    }

    public void Move()
    {
        _wheel.Rotate();
        Console.WriteLine("Vehicle is moving.");
    }
}

// Example usage
class Program
{
    static void Main()
    {
        // Inject the dependency
        IWheel carWheel = new CarWheel();
        Vehicle car = new Vehicle(carWheel);

        // Move the vehicle
        car.Move();  // Output: "Car wheel is rotating. Vehicle is moving."
    }
}

Enter fullscreen mode Exit fullscreen mode

3. Master Entity Framework Core Basics

To effectively use EF with ASP.NET Core, focus on:

DbContext: DbContext is probably one of the most important concepts/tools you’ll need to understand in EF. DbContext is the main class in EF that acts as a translator between your application and database. It manages the connection and handles changes to the data. It encapsulates your model classes (representing tables in the database) and translates your C# code into database queries, simplifying how you interact with the database.

using Microsoft.EntityFrameworkCore;

public class AppDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }  // Represents the Products table

    // Configuring the database connection string
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Replace "YourConnectionStringHere" with your actual database connection string
        optionsBuilder.UseSqlServer("YourConnectionStringHere");
    }
}

using System;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        using (var context = new AppDbContext())
        {
            // Querying all products
            var products = context.Products.ToList();
            Console.WriteLine("List of Products:");
            foreach (var product in products)
            {
                Console.WriteLine($"Id: {product.Id}, Name: {product.Name}, Price: {product.Price}");
            }

            // Adding a new product
            var newProduct = new Product
            {
                Name = "Laptop",
                Price = 1200.00m
            };

            context.Products.Add(newProduct);  // Add the new product to the DbSet
            context.SaveChanges();  // Save changes to the database

            Console.WriteLine("New product added.");
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Code First Migrations: Code First Migrations allow developers to define a database schema using C# model classes and manage changes incrementally. Unlike manual SQL scripting (as required in tools like Knex.js), EF simplifies the process by automatically generating the database schema and migrations based on your model definitions. After making changes to your models, EF can update the database structure for you, enabling you to manage your database entirely through C# code.

//C# example
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

dotnet ef migrations add InitialCreate

dotnet ef database update

//SQL example
CREATE TABLE Product (
    Id INT PRIMARY KEY IDENTITY(1,1), -- Auto-incrementing primary key
    Name NVARCHAR(255) NOT NULL,     -- String with a maximum length of 255 characters
    Price DECIMAL(18, 2) NOT NULL    -- Decimal with precision 18 and scale 2
);

Enter fullscreen mode Exit fullscreen mode

LINQ Queries: LINQ (Language Integrated Query) is a querying language that allows developers to write SQL-like queries directly in C#. At runtime, LINQ queries are translated into raw SQL when interacting with a database through Entity Framework. But for more complex queries, raw SQL can be used alongside LINQ in EF.

//LINQ example
var expensiveProducts = dbContext.Products.Where(p => p.Price > 100);
//SQL example
SELECT * FROM Products WHERE Price > 100;

Enter fullscreen mode Exit fullscreen mode

4. Leverage Documentation and Online Resources

One of the biggest challenges I faced in the early stages of learning ASP.NET Core was not knowing where to start. While ASP.NET Core resources are abundant, I found that many of them were not beginner-friendly or simply disengaging. CodeCademy was a great resource to learn C# but I found that wasn’t the case for ASP.NET Core. As a result, I spent a lot of time filtering through resources recommended by seasoned C# developers on Reddit for succinct, easy-to-digest material.

I recommend using the official ASP.NET Core documentation as a primary source of truth and guidance. The team at Microsoft does a great job at breaking down this robust framework not only through documentation but also in videos that are great for people who are visual and auditory learners. For supplementary learning, I found that YouTube has some gems that offer high-quality tutorials and courses.

Here are the resources I used and recommend:
Microsoft's Back-end Web Development for Beginners

Microsoft's Entity Framework Tutorial Document

Microsoft's Entity Framework Youtube Playlist

Full Course on ASP.NET by Julio Casal

5. Embrace Iterative Learning

There were times when learning ASP.NET Core felt like a time loop, rewatching tutorials or courses multiple times. But persistence is key. It’s easy to get discouraged when things aren’t clicking, but improvement comes from iterating on what confuses you and learning from mistakes. Rewatch that Dependency Injection video, redo the same tutorial, or find a new resource to reinforce key concepts. As a software developer, problem-solving and persistence are essential skills that will help you succeed with ASP.NET Core.

Conclusion
Looking back on my journey to learn ASP.NET Core, I can confidently say that persistence, trial and error, and a willingness to embrace challenges were key to my progress. When I first encountered ASP.NET Core, it felt overwhelming and uncertain. But by breaking it down into manageable steps, following along side tutorials, and asking questions, I was able to make the transition. Learning is a continuous journey—ASP.NET Core may seem complex at first, but once you find your learning sweet spot, it becomes a rewarding experience.

Top comments (0)