Implementing Entity Framework: Code-First Approach

vzldev

VzlDev

Posted on March 15, 2024

Implementing Entity Framework: Code-First Approach

Hello guys! In this post I'm talk a little bit about Entity Framework (EF), and how to implement it using the code-first approach.

Entity Framework is an open-source object-relational mapping (ORM) framework for .NET applications developed by Microsoft. It simplifies the process of interaction with databases.

Why choosing Entity Framework?

Using EF has several advantages like:

  • Simplifies the interactions with databases.

  • Provides a high-level abstraction over the underlying database, hiding complex SQL queries.

  • Supports LINQ (Language Integrated Query).

  • Supports multiple database providers.

Lets start with the implementation of Entity Framework. For this tutorial I will use a scenario of TV Shows and store them in a db, with the possibility to execute CRUD operations on them.

Step 1

First of all you need to create a new .NET project.

Step 2

Install the Entity Framework Core in your project:

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.Design
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Enter fullscreen mode Exit fullscreen mode

Step 3

Add the Connection string to the Appsettings.json

"ConnectionStrings": {
    "TvShowContext": "Server=(localdb)\\MSSQLLocalDB;Database=TvShows;Integrated Security=True;"
  }
Enter fullscreen mode Exit fullscreen mode

Step 4

You need to create your model (for this tutorial only the TvShow.cs will be created)

public class TvShow
    {
        [Key]
        public int Id { get; set; }

        public string Name { get; set; }

        public double ImdbRating { get; set; }

        public TvShow()
        {
        }
    }
Enter fullscreen mode Exit fullscreen mode

Step 5

When you complete the creation of your model, it's time to set up the database context. This is the class that will allow interactions with the database.

public partial class TvShowContext : DbContext
    {
        public TvShowContext(DbContextOptions
        <TvShowContext> options)
            : base(options)
        {
        }
        public DbSet<TvShow> TvShows { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<TvShow>(entity =>
            {
                entity.HasKey(k => k.Id);
            });
            OnModelCreatingPartial(modelBuilder);
        }
        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
Enter fullscreen mode Exit fullscreen mode

Step 6

Now you need to update your Program.cs to add the database connection.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

//Add your connectionString and DBContext
var connectionString = builder.Configuration.GetConnectionString("TvShowContext");
builder.Services.AddDbContext<TvShowContext>(options => options.UseSqlServer(connectionString));

builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Enter fullscreen mode Exit fullscreen mode

Step 7

In this step you will run the first database migration, to create your database and table if it doesn't exist.
Open the Package Manager Console in the Visual Studio and run the following command:

ADD-MIGRATION {MigrationName}

This command will create a new folder "Migrations" in your project containing the migration files.

Image description

Now that the migration is created you must apply the migration to the database using the following command:

Update-Database

Now you can go check the changes to your database.

Step 8

Now that you have all set up, it's time to create your controller to handle the requests for CRUD operations.

[Route("[controller]")]
    [ApiController]
    public class TvShowsController : ControllerBase
    {
        private readonly TvShowContext _context;

        public TvShowsController(TvShowContext context)
        {
            _context = context;
        }

        [HttpGet]
        public ActionResult<IEnumerable<TvShow>> GetTvShows()
        {
            return _context.TvShows.ToList();
        }

        [HttpGet("{id}")]
        public ActionResult<TvShow> GetTvShow(int id)
        {
            var tvshow = _context.TvShows.Find(id);
            if (tvshow == null)
            {
                return NotFound();
            }
            return tvshow;
        }

        [HttpPost]
        public ActionResult<TvShow> CreateTvShow(TvShow tvShow)
        {
            if (tvShow == null)
            {
                return BadRequest();
            }
            _context.TvShows.Add(tvShow);
            _context.SaveChanges();
            return Ok();
        }

        [HttpDelete("{id}")]
        public ActionResult DeleteTvShow(int id)
        {
            var tvshow = _context.TvShows.Find(id);
            if (tvshow == null)
            {
                return NotFound();
            }
            _context.TvShows.Remove(tvshow);
            _context.SaveChanges();
            return NoContent();
        }

        [HttpPut("{id}")]
        public ActionResult<TvShow> UpdateTvShow(int id, TvShow tvShow)
        {
            var existingTvShow = _context.TvShows.Find(id);
            if (existingTvShow == null)
            {
                return NotFound();
            }

            existingTvShow.Name = tvShow.Name;
            existingTvShow.ImdbRating = tvShow.ImdbRating;

            _context.SaveChanges();
            return NoContent();
        }
Enter fullscreen mode Exit fullscreen mode

Step 9

Finally you can run your projects and use postman to do your requests, like for example:

Image description

Image description

I hope you liked it, stay tuned for more!

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
vzldev
VzlDev

Posted on March 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About