Simple Database Manipulation
Querying
Inserting
Use DbSet.AddAsync
to track the given object. Use DbSet.SaveChangesAsync
to apply tracked insertions.
cs
[HttpPost]
[ProducesResponseType(typeof(Movie), StatusCodes.Status201Created)]
public async Task<IActionResult> Create([FromBody] Movie movie)
{
await context.Movies.AddAsync(movie);
await context.SaveChangesAsync();
// ..
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Auto-assign id
When posting request to insert new records, id is not required, it should be auto-generated. EFCore can handle this behind the scene. Once DbContext.SaveChangesAsync
is invoked, EFCore auto calculates the id from database for the added object.
cs
[HttpPost]
[ProducesResponseType(typeof(Movie), StatusCodes.Status201Created)]
public async Task<IActionResult> Create([FromBody] Movie movie)
{
await context.Movies.AddAsync(movie);
await context.SaveChangesAsync();
return CreatedAtAction(nameof(Get), new { id = movie.Id }, movie);
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Updating
EFCore keep tracking the queried object, any modification will be handled when SaveChangesAsync
invoked.
cs
[HttpPut("{id:int}")]
[ProducesResponseType(typeof(Movie), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Update([FromRoute] int id, [FromBody] Movie movie)
{
Movie? existing = await context.Movies.FindAsync(id);
if (existing is null)
return NotFound();
(existing.Title, existing.Synopsis, existing.ReleaseDate) =
(movie.Title, movie.Synopsis, movie.ReleaseDate);
await context.SaveChangesAsync();
return Ok(existing);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
Deleting
cs
[HttpDelete("{id:int}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Remove([FromRoute] int id)
{
Movie? existing = await context.Movies.FindAsync(id);
if (existing is null)
return NotFound();
context.Movies.Remove(existing);
// can also delete from dbcontext since there's only one DbSet<Movie> in it.
// context.Remove(existing);
await context.SaveChangesAsync();
return Ok();
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
Also, EFCore knows how to find the row to delete by unique property.
cs
[HttpDelete("{id:int}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Remove([FromRoute] int id)
{
// still need to guard here but I just omit it...
context.Movies.Remove(new Movie { Id = id }); // Just delete by id!
await context.SaveChangesAsync();
return Ok();
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10