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:
The Code-First approach offers several advantages that cater to application development and database design:
- 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.
- Database Schema Generation: EF automatically generates the database schema based on the entity classes, saving time on manual database setup.
- 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.csusing 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.csusing 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.csusing 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
This will now create a new folder names “Migrations” and that will contain your migration files
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
Once the migration has been applied you can validate your database to see if changes are applied to the database.
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.csusing 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
- 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.
- 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 theCustomerController
. - For example:
- To retrieve all customers:
https://localhost:5001/api/Customer
- To retrieve a specific customer:
https://localhost:5001/api/Customer/1
- To create a new customer, use a tool like Postman or cURL to make an HTTP POST request to
https://localhost:5001/api/Customer
with the JSON payload containing the details of the new customer.
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.