CRUD ASP.NET Core Using Entity Framework Core With Swagger

In this article, we are creating a CRUD website with entity framework using .Net Core and Swagger.

Base article

 
This article is going to handle the connection of an existent website to a local database using entity framework Core. So, the starting point is going to be the following article:

What is Entity Framework Core?

 
EF Core is a lightweight, extensible, and cross-platform version of Entity Framework Read more about Entity Framework Core

Benefits of using Entity Framework Core

  • Faster database set up;
  • Easier to access data, reducing time to read and access data;
  • Work directly with your complex objects, not to dataset/datatables;
  • Less code, more control;
  • No need to write queries, we use LINQ to Entities.

Entity Framework vs Entity Framework Core

 
Entity framework
  • Runs only on Windows;
  • Can be used with .Net Framework;
  • No more new features will be added in here.
Entity Framework Core
  • Is Cross-platform, so is not executable only on Windows; 
  • Can be used with .Net Core or .Net Framework;
  • Keeps growing and getting better every day.
 

CRUD Implementation Step by Step

 
Adjust the model in order to make it able to be stored into a database,
  1. public class ValueSamples  
  2. {  
  3.     [Key]
  4.     public int Id { getset; }  
  5.     public string Name { getset; }    
  6. }  

Create your DB context file

This is the class that is going to connect to your database, each object declared inside DbSet type is going to be a table.
  1. public class CrudSampleContext : DbContext  
  2.     {  
  3.         public CrudSampleContext(DbContextOptions<CrudSampleContext> options) : base(options)  
  4.         {  
  5.         }  
  6.   
  7.         public DbSet<ValueSamples> ValueSamples { getset; }  
  8.     }  

Adjust your StartUp class

You must register and initialize your DB context using dependency injection.
  1. public void ConfigureServices( IServiceCollection services )  
  2.         {  
  3.             services.AddMvc().SetCompatibilityVersion( CompatibilityVersion.Version_2_1 );  
  4.             services.AddDbContext<CrudSampleContext>(options => options.UseSqlServer("your database connection string"));  
  5.   
  6.             // Register Swagger  
  7.             services.AddSwaggerGen( c =>  
  8.             {  
  9.                 c.SwaggerDoc( "v1"new Info { Title = "Sample API", Version = "version 1" } );  
  10.             } );  
  11.         }  
Getting your database connection string
  • Open Server Explorer and click on "Connect to Database".

    CRUD ASP.NET Core Using Entity Framework Core With Swagger

  • Select Microsoft SQL Server.

    CRUD ASP.NET Core Using Entity Framework Core With Swagger

  • Pick up your server name and push OK.

    CRUD ASP.NET Core Using Entity Framework Core With Swagger

  • Check the result.

    CRUD ASP.NET Core Using Entity Framework Core With Swagger

  • Right-click on your newly added Data Connection and go to properties.

    CRUD ASP.NET Core Using Entity Framework Core With Swagger

  • Get your connection string.

    CRUD ASP.NET Core Using Entity Framework Core With Swagger

  • Your final Start Up class
    With your connection string, your StartUp should look like this.
The items in yellow were added from the connection string above.
  1. public class Startup  
  2.     {  
  3.         public Startup( IConfiguration configuration )  
  4.         {  
  5.             Configuration = configuration;  
  6.         }  
  7.   
  8.         public IConfiguration Configuration { get; }  
  9.   
  10.         // This method gets called by the runtime. Use this method to add services to the container.  
  11.         public void ConfigureServices( IServiceCollection services )  
  12.         {  
  13.             services.AddMvc().SetCompatibilityVersion( CompatibilityVersion.Version_2_1 );  
  14.             services.AddDbContext<CrudSampleContext>(options => options.UseSqlServer(@"Data Source=yourServer;Integrated Security=True;Database=CRUDSample"));  
  15.   
  16.             // Register Swagger  
  17.             services.AddSwaggerGen( c =>  
  18.             {  
  19.                 c.SwaggerDoc( "v1"new Info { Title = "Sample API", Version = "version 1" } );  
  20.             } );  
  21.         }  
  22.   
  23.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  24.         public void Configure( IApplicationBuilder app, IHostingEnvironment env )  
  25.         {  
  26.             if ( env.IsDevelopment() )  
  27.             {  
  28.                 app.UseDeveloperExceptionPage();  
  29.   
  30.                 // Enable middleware to serve generated Swagger as a JSON endpoint.  
  31.                 app.UseSwagger();  
  32.   
  33.                 // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),  
  34.                 // specifying the Swagger JSON endpoint.  
  35.                 app.UseSwaggerUI( c =>  
  36.                 {  
  37.                     c.SwaggerEndpoint( "/swagger/v1/swagger.json""My API V1" );  
  38.                 } );  
  39.             }  
  40.   
  41.             app.UseMvc();  
  42.         }  
  43.     }  
Create your database
  • Add initial migration
    Open your Package Manager Console (PMC) and create your initial migration

    CRUD ASP.NET Core Using Entity Framework Core With Swagger

    Check the new folder in your project solution

    CRUD ASP.NET Core Using Entity Framework Core With Swagger

  • Create the database
    Run the command update-database

    CRUD ASP.NET Core Using Entity Framework Core With Swagger 

    Check your new Database in your SQL Server Management Studio

    CRUD ASP.NET Core Using Entity Framework Core With Swagger 

CRUD Samples

 
Remember, to access your Api through swagger you must go to swagger endpoint. In my case, it is - http://localhost:61986/swagger/index.html
 
Update your controller actions
  • Get

    • Code 
      1. [HttpGet]    
      2. public ActionResult<List<ValueSamples>> Get()    
      3. {    
      4.     var itemLst = _crudSampleContext.ValueSamples.ToList();    
      5.     return new List<ValueSamples>(itemLst);    
      6. }   
    • Result from swagger

      CRUD ASP.NET Core Using Entity Framework Core With Swagger

    • Database

      CRUD ASP.NET Core Using Entity Framework Core With Swagger

  • Create

    • Code
      1. [HttpPost]    
      2.  public void Post([FromBody] ValueSamples createSample)    
      3.  {    
      4.      _crudSampleContext.ValueSamples.Add(createSample);    
      5.      _crudSampleContext.SaveChanges();    
      6.  }  
    • Swagger

      CRUD ASP.NET Core Using Entity Framework Core With Swagger

    • Database

      CRUD ASP.NET Core Using Entity Framework Core With Swagger

  • Update

    • Code
      1. [HttpPut]    
      2. public void Put([FromBody] ValueSamples updateSample)    
      3. {    
      4.     _crudSampleContext.ValueSamples.Update(updateSample);    
      5.     _crudSampleContext.SaveChanges();    
      6. }    
    • Swagger

      CRUD ASP.NET Core Using Entity Framework Core With Swagger

    • Database

      CRUD ASP.NET Core Using Entity Framework Core With Swagger

  • Delete

    • Code
      1. [HttpDelete("{id}")]    
      2. public void Delete(int id)    
      3. {    
      4.     var itemToDelete = _crudSampleContext.ValueSamples.Where(x => x.Id == id).FirstOrDefault();    
      5.     _crudSampleContext.ValueSamples.Remove(itemToDelete);    
      6.     _crudSampleContext.SaveChanges();    
      7. }  
    • Swagger

      CRUD ASP.NET Core Using Entity Framework Core With Swagger

    • Database

      CRUD ASP.NET Core Using Entity Framework Core With Swagger

  • Single Get

    • Code
      1. [HttpGet("{id}")]    
      2. public ActionResult<string> Get(int id)    
      3. {    
      4.     var itemToReturn = _crudSampleContext.ValueSamples.Where(x => x.Id == id).FirstOrDefault();    
      5.     return itemToReturn.Name;    
      6. }   
    • Swagger

      CRUD ASP.NET Core Using Entity Framework Core With Swagger

Your controller must look like this,

  1. [Route("api/[controller]")]  
  2.     [ApiController]  
  3.     public class ValuesController : ControllerBase  
  4.     {  
  5.         private readonly CrudSampleContext _crudSampleContext;  
  6.         public ValuesController(CrudSampleContext crudSampleContext)  
  7.         {  
  8.             this._crudSampleContext = crudSampleContext;  
  9.         }  
  10.   
  11.         // GET api/values  
  12.         [HttpGet]  
  13.         public ActionResult<List<ValueSamples>> Get()  
  14.         {  
  15.             var itemLst = _crudSampleContext.ValueSamples.ToList();  
  16.             return new List<ValueSamples>(itemLst);  
  17.         }  
  18.   
  19.         // GET api/values/5  
  20.         [HttpGet("{id}")]  
  21.         public ActionResult<string> Get(int id)  
  22.         {  
  23.             var itemToReturn = _crudSampleContext.ValueSamples.Where(x => x.Id == id).FirstOrDefault();  
  24.             return itemToReturn.Name;  
  25.         }  
  26.   
  27.         // POST api/values  
  28.         [HttpPost]  
  29.         public void Post([FromBody] ValueSamples createSample)  
  30.         {  
  31.             _crudSampleContext.ValueSamples.Add(createSample);  
  32.             _crudSampleContext.SaveChanges();  
  33.         }  
  34.   
  35.         // PUT api/values/5  
  36.         [HttpPut]  
  37.         public void Put([FromBody] ValueSamples updateSample)  
  38.         {  
  39.             _crudSampleContext.ValueSamples.Update(updateSample);  
  40.             _crudSampleContext.SaveChanges();  
  41.         }  
  42.   
  43.         // DELETE api/values/5  
  44.         [HttpDelete("{id}")]  
  45.         public void Delete(int id)  
  46.         {  
  47.             var itemToDelete = _crudSampleContext.ValueSamples.Where(x => x.Id == id).FirstOrDefault();  
  48.             _crudSampleContext.ValueSamples.Remove(itemToDelete);  
  49.             _crudSampleContext.SaveChanges();  
  50.         }  
  51.     }  
Congratulations, you have successfully implemented your CRUD using Entity Framework Core.

External References