How to connect .NET Web API with SQL Server using Entity Framework: Code-First Approach (2024)

How to connect.NET Web API with SQL Server using Entity Framework: Code-First Approach (2)

In the previous article, we explored how to connect a .NET Web API with SQL Server using Entity Framework in the Database-First approach. We learned about the benefits of Entity Framework, the Database-First approach, and its advantages when working with an existing database. In this continuation article, we will delve into the Code-First approach, which involves defining the entity classes and their relationships in code first, and then letting EF generate the database schema automatically based on these classes.

Read the previous article if you want to learn more about the Database-First approach:

How to Connect .NET Web API with SQL Server using Entity FrameworkIn today’s data-driven world, building web applications that interact with databases is a common requirement. .NET…medium.com

The Code-First approach offers several advantages that cater to application development and database design:

  1. Control over Entities: Developers have full control over the entity classes, allowing them to define relationships, data annotations, and custom configurations directly in the code.
  2. Database Schema Generation: EF automatically generates the database schema based on the entity classes, saving time on manual database setup.
  3. Flexibility: Code-First allows developers to evolve the database schema seamlessly along with application changes using migrations.

Lets now get our hands dirty by creating an Api with code-first appraoch

Step 1: Create a .NET Web API Project

Let’s create a new .NET Web API project using Visual Studio or the .NET CLI:

dotnet new webapi -n DotnetWebApiWithEFCodeFirst

Alternatively you can create a new project from Visual Studio

  • Open Visual Studio and select “Create a Project”
  • Select “ASP.NET Core Web API” or any other type of project you want to create
  • Give your project a name, I am using “DotnetWebApiWithEFCodeFirst” and then click on create.
  • This will create a new project.

Step 2: Install Entity Framework Core

In the project directory, install the Entity Framework Core package using the following command:

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
dotnet add package Microsoft.EntityFrameworkCore.Design

Alternatively you can install these package from “Mange Nuget Package” section available in Visual Studio.

Step 3: Define Entity Classes

Unlike the Database-First approach, we will not generate entity classes from the existing database. Instead, we will manually define them in code. Create a folder named “Models” and add the following class for the Customer entity:

// Models/Customer.cs

using System.ComponentModel.DataAnnotations;

namespace DotnetWebApiWithEFCodeFirst.Models
{
public class Customer
{
[Key]
public int CustomerId { get; set; }
[Required]
[MaxLength(50)]
public string FirstName { get; set; }
[Required]
[MaxLength(50)]
public string LastName { get; set; }
[Required]
[MaxLength(100)]
public string Email { get; set; }
}
}

Step 4: Create the Database Context

Next, create the database context class that derives from DbContext. This class will represent the database and allow us to interact with it.

// Models/SampleDBContext.cs

using Microsoft.EntityFrameworkCore;

namespace DotnetWebApiWithEFCodeFirst.Models
{
public partial class SampleDBContext : DbContext
{
public SampleDBContext(DbContextOptions
<SampleDBContext> options)
: base(options)
{
}
public virtual DbSet<Customer> Customer { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>(entity => {
entity.HasKey(k => k.CustomerId);
});
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
}

Step 5: Configure Database Connection

In the Program.cs file, configure the database connection and add the database context to the DI container:

// Startup.cs

using DotnetWebApiWithEFCodeFirst.Models;
using Microsoft.EntityFrameworkCore;

namespace DotnetWebApiWithEFCodeFirst
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
//This section below is for connection string
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<SampleDBContext>(options => options.UseSqlServer(connectionString));

builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
}
}
}

Step 6: Configure Connection String

In the appsettings.json file, add the connection string for your SQL Server database:

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Server=tcp:YOUR_SERVER,1433;Initial Catalog=YOUR_DATABSE;Persist Security Info=False;User ID=YOUR_USER_ID;Password=YOUR_PASSWORD;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
}
}

Modify the connection string as per your actual connection string

Step 7: Run Database migration

This is the import step, here we will create a new migration for our customer model

Open Package Manger Console in the Visual Studio. You can find this option in Views => Other Windows => Package Manager Console.

Once Package Manage Console is open, run below command

ADD-MIGRATION MyFirstMigration

This will create a new migration and output would look something like this

How to connect.NET Web API with SQL Server using Entity Framework: Code-First Approach (3)

This will now create a new folder names “Migrations” and that will contain your migration files

How to connect.NET Web API with SQL Server using Entity Framework: Code-First Approach (4)

These are the changes that are going to be committed into the database when you run your migration. Now you can review these and if you are good you can proceed with committing your migration.

Step 8: Apply the migration

Now that we you good with the changes, apply the migration using the below command

UPADE-DATABASE

This will apply the migration into the database

How to connect.NET Web API with SQL Server using Entity Framework: Code-First Approach (5)

Once the migration has been applied you can validate your database to see if changes are applied to the database.

How to connect.NET Web API with SQL Server using Entity Framework: Code-First Approach (6)

Step 9: Remove or Revert a Migration

To remove the last applied migration in Entity Framework Core, you can use either the “Remove-Migration” command in the Package Manager Console or “dotnet ef migrations remove” in the terminal. For example:

Remove-Migration

This command removes the most recent migration, updating the database schema to match the state before the last migration.

To revert the database to a specific migration, you can use the “update-database” command with the migration name. For instance:

Update-database MyFirstMigration

This command rolls back changes in the database to the state defined by the specified migration. Migrations in Entity Framework Core provide a structured approach to managing and applying database schema changes efficiently.

Step 10: Create the Web API Controller

Create a controller for the Customer entity to handle CRUD operations:

// Controllers/CustomerController.cs

using DotnetWebApiWithEFCodeFirst.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DotnetWebApiWithEFCodeFirst.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CustomerController : ControllerBase
{
private readonly SampleDBContext _context;
public CustomerController(SampleDBContext context)
{
_context = context;
}

// GET: api/Customer
[HttpGet]
public ActionResult<IEnumerable<Customer>> GetCustomers()
{
return _context.Customer.ToList();
}

// GET: api/Customer/1
[HttpGet("{id}")]
public ActionResult<Customer> GetCustomer(int id)
{
var customer = _context.Customer.Find(id);
if (customer == null)
{
return NotFound();
}
return customer;
}

// POST: api/Customer
[HttpPost]
public ActionResult<Customer> CreateCustomer(Customer customer)
{
if (customer == null)
{
return BadRequest();
}
_context.Customer.Add(customer);
_context.SaveChanges();
return CreatedAtAction(nameof(GetCustomer), new { id = customer.CustomerId }, customer);
}
}
}

Step 11: Run the Web API Application

Now, run the Web API application using the following command:

dotnet run
  1. If everything is set up correctly, the command prompt or terminal will display messages indicating the successful execution of the application. This will include log messages and information about the hosting environment.
  2. Once the application is running, you can open a web browser or use tools like Postman to interact with the Web API. The API endpoints can be accessed using the base URL specified in the [Route] attribute of the CustomerController.
  3. For example:

With this continuation article, you have now learned how to connect a .NET Web API with SQL Server using Entity Framework in the Code-First approach. The Code-First approach empowers developers to have more control over entities and automatically generate the database schema, making it an excellent choice for application development and database design.

Happy coding!

And that’s a wrap! If you’ve read this far, it means you liked this article. If that’s true, please leave a clap. I publish similar articles every week, so feel free to follow me for more.

How to connect.NET Web API with SQL Server using Entity Framework: Code-First Approach (7)
How to connect .NET Web API with SQL Server using Entity Framework: Code-First Approach (2024)
Top Articles
Latest Posts
Article information

Author: Kelle Weber

Last Updated:

Views: 6011

Rating: 4.2 / 5 (53 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Kelle Weber

Birthday: 2000-08-05

Address: 6796 Juan Square, Markfort, MN 58988

Phone: +8215934114615

Job: Hospitality Director

Hobby: tabletop games, Foreign language learning, Leather crafting, Horseback riding, Swimming, Knapping, Handball

Introduction: My name is Kelle Weber, I am a magnificent, enchanting, fair, joyous, light, determined, joyous person who loves writing and wants to share my knowledge and understanding with you.