8.6 C
New York
Thursday, January 25, 2024

Demystifying the Code First method in EF Core


Once we construct database-backed enterprise functions, we typically wish to isolate our entity fashions, the DbContext, and the logic for database initialization and migration to take care of a clear structure. We are able to do that by profiting from the Code First method in Entity Framework Core.

This text presents a dialogue of the Code First method in EF Core with code examples for example the ideas. To make use of the code examples supplied on this article, it is best to have Visible Studio 2022 put in in your system. In case you don’t have already got a replica, you possibly can obtain Visible Studio 2022 right here.

Create an ASP.NET Core Internet API undertaking in Visible Studio

To create an ASP.NET Core Internet API undertaking in Visible Studio 2022, comply with the steps outlined under.

  1. Launch the Visible Studio 2022 IDE.
  2. Click on on “Create new undertaking.”
  3. Within the “Create new undertaking” window, choose “ASP.NET Core Internet API” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new undertaking” window, specify the identify and site for the brand new undertaking.
  6. Optionally verify the “Place resolution and undertaking in the identical listing” verify field, relying in your preferences.
  7. Click on Subsequent.
  8. Within the “Extra Info” window proven subsequent, choose “.NET 8.0 (Lengthy Time period Assist)” because the framework model and be sure that the “Use controllers” field is checked. We received’t be utilizing minimal APIs on this undertaking.
  9. Elsewhere within the “Extra Info” window, depart “Authentication Kind” set to “None” (the default) and ensure the verify containers “Allow Open API Assist,” “Configure for HTTPS,” and “Allow Docker” stay unchecked. We received’t be utilizing any of these options right here.
  10. Click on Create.

We’ll use this ASP.NET Core Internet API undertaking to work with EF Core and the Code First method within the sections under.

Creating an entity mannequin in EF Core

Microsoft’s EF Core is an object-database mapper that simplifies information entry for .NET Core functions. EF Core works with relational databases, non-relational databases, and even in-memory databases, and permits us to write down code to carry out CRUD (create, learn, replace, delete) operations that use .NET objects. Through the use of EF Core, we don’t should work together straight with the underlying database supplier.

EF Core helps three completely different approaches to create the entity mannequin: Code First, Mannequin First, and Database First.

The Code First method in EF Core

Within the Code First method, the entity mannequin is outlined utilizing code with none pre-existing database schema. Builders write area lessons and configure the mapping between these lessons and the database utilizing attributes, fluent APIs, or conventions. EF Core then creates the database schema based mostly on the code-defined mannequin. The Code First method permits you to categorical complicated relationships utilizing code. It’s usually most popular when the database schema is unavailable.

The Mannequin First method in EF Core

Within the Mannequin First method, the entity mannequin is designed utilizing a visible design software, such because the Entity Framework Designer in Visible Studio. With the designer, builders can visually create entities, relationships, and different features of an information mannequin with out writing a single line of code. When you’ve outlined the mannequin, EF Core generates the code, together with the entity lessons and the mapping configurations. You’ll be able to later lengthen the code so as to add enterprise logic or customizations as acceptable. Mannequin First could be useful when non-developers are concerned in defining the information mannequin or when an present database schema must be reverse-engineered.

The Database First method in EF Core

Within the Database First method, an present database schema is used to generate the entity mannequin utilizing EF Core instruments. These instruments can generate entity lessons and mapping configurations by reverse engineering the database schema. It is usually doable to synchronize database schema adjustments with the entity mannequin. When builders use the Database First method, they acquire extra management over the database construction however much less management over the code mannequin. This method is an efficient alternative when integrating EF Core with an present database or working with legacy databases.

Utilizing the Code First method in EF Core

Earlier than you should use EF Core in your software, you have to add the Microsoft.EntityFrameworkCore bundle to your undertaking. To do that, choose the undertaking within the Answer Explorer window, then right-click and choose “Handle NuGet Packages.” Within the NuGet Bundle Supervisor window, seek for the Microsoft.EntityFrameworkCore bundle and set up it.

Alternatively, you possibly can set up the bundle by way of the NuGet Bundle Supervisor console by getting into the command under.

PM> Set up-Bundle Microsoft.EntityFrameworkCore

With that out of the best way, let’s now create an information mannequin utilizing the Code First method in EF Core. We’ll do that in 5 steps: Outline the area lessons, create the DbContext class, configure the DbContext, register the DbContext, and at last migrate the database.

Step 1: Outline your area lessons

Begin by creating the area lessons that correspond to the entities in your software. The next code snippet defines an Creator class and its members.

public class Creator
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Handle { get; set; }
}

Step 2: Create the DbContext class

Create a category that extends the DbContext class of EF Core. This class represents your database context and is the gateway to all communications between your software and the database. In different phrases, the DbContext class acts because the entry level for performing CRUD operations on the information.

public class AuthorDbContext : DbContext
{
    public DbSet<Creator> Authors { get; set; }
    public AuthorDbContext(DbContextOptions<AuthorDbContext> choices)
        : base(choices)
    {
    }
}

Word how the DbContextOptions occasion is handed to the constructor of this class. This occasion will include the database supplier and connection string info your software wants to hook up with the database.

Step 3: Configure the DbContext

Subsequent override the OnModelCreating technique of your AuthorDbContext class to configure the mannequin and its relationships as proven within the code snippet under.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Creator>()
        .Property(p => p.FirstName).IsRequired().HasMaxLength(50);
}

Step 4: Register the DbContext

Now register the AuthorDbContext with the dependency injection container utilizing the next code snippet. This can permit your software to entry the DbContext occasion all through its life cycle.

builder.Companies.AddDbContext<AuthorDbContext>(choices =>     
choices.UseSqlServer(Configuration.GetConnectionString("AuthorDb")));

Step 5: Migrate the database

On this last step we reap the benefits of the migration characteristic of EF Core to create or replace the database schema based mostly on our information mannequin. To do that, run the next command on the EF Core CLI window or the NuGet Bundle Supervisor console.

dotnet ef migrations add InitialMigration

And that’s all it’s a must to do to get your software up and working utilizing the Code First method.

Every of the three approaches to creating an information mannequin in EF Core has its execs and cons. You need to choose the proper method to your software relying on the necessities. I’ll talk about the opposite two approaches, Mannequin First and Database First, intimately in future posts right here.

Copyright © 2024 IDG Communications, Inc.



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles