Problem
How to implement CRUD using Entity Framework Core and ASP.NET Core.
Solution
Create a class library and add the following NuGet package.
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.Relational
- Microsoft.EntityFrameworkCore.SqlServer
Create a class representing the database entity.
public class Actor
{
public int Id { get; set; }
public string Name { get; set; }
}
Create a class inheriting from DbContext.
public class Database : DbContext
{
public Database(DbContextOptions<Database> options) : base(options) { }
public DbSet<Actor> Actors { get; set; }
}
Create ASP.NET Core web application and an API controller for CRUD operations. To retrieve a list and a single item.
[HttpGet]
public async Task<IActionResult> GetList()
{
var entities = await context.Actors.ToListAsync();
var outputModel = entities.Select(entity => new
{
entity.Id,
entity.Name,
});
return Ok(outputModel);
}
[HttpGet("{id}", Name = "GetActor")]
public IActionResult GetItem(int id)
{
var entity = context.Actors
.Where(e => e.Id == id)
.FirstOrDefault();
if (entity == null)
return NotFound();
var outputModel = new
{
entity.Id,
entity.Name,
};
return Ok(outputModel);
}
To insert a new item
[HttpPost]
public async Task<IActionResult> Create([FromBody] ActorCreateInputModel inputModel)
{
if (inputModel == null)
return BadRequest();
var entity = new Actor
{
Name = inputModel.Name
};
this.context.Actors.Add(entity);
await this.context.SaveChangesAsync();
var outputModel = new
{
entity.Id,
entity.Name
};
return CreatedAtRoute("GetActor", new { id = outputModel.Id }, outputModel);
}
To update an existing item
[HttpPut("{id}")]
public IActionResult Update(int id, [FromBody] ActorUpdateInputModel inputModel)
{
if (inputModel == null || id != inputModel.Id)
return BadRequest();
var entity = new Actor
{
Id = inputModel.Id,
Name = inputModel.Name
};
this.context.Actors.Update(entity);
this.context.SaveChanges();
return NoContent();
}
To delete an item
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var entity = context.Actors
.Where(e => e.Id == id)
.FirstOrDefault();
if (entity == null)
return NotFound();
this.context.Actors.Remove(entity);
this.context.SaveChanges();
return NoContent();
}
Configure the DbContext in Startup
public void ConfigureServices(IServiceCollection services)
{
var connection = "Data Source=...";
services.AddDbContext<Database>(options =>
options.UseSqlServer(connection));
services.AddMvc();
}
Discussion
Entity Framework Core (EF) is an ORM that makes it simpler to work with the database by using POCO classes that map to database entities and DbContext to interact with them.
Configuring DbContext
As shown in the code (Solution section), the best (and testable) way to configure DbContextsubclass is to inject DbContextOptions in its constructor. NuGet package Microsoft.EntityFrameworkCore provides an extension method AddDbContext to setup custom DbContext (as shown in Solution section). You could, however, also add the dependency like this.
services.AddScoped(factory =>
{
var builder = new DbContextOptionsBuilder<Database>();
builder.UseSqlServer(connection);
return new Database(builder.Options);
});
Saving
Your subclass of DbContext will have a DbSet of entities, through which you could add, update and remove database records. SaveChanges() method on DbContext triggers the database changes, which means that you could also add/update/remove multiple items in one transaction
this.context.Actors.Add(entity1);
this.context.Actors.Add(entity2);
this.context.Actors.Add(entity3);
await this.context.SaveChangesAsync();
Note.There is a synchronous and asynchronous version of the SaveChanges() method.
Querying
Join the conversation! Your thoughts help the community grow.