Saving data

The DbContext class provided by EF Core is designed to work as a Unit Of Work (https://martinfowler.com/eaaCatalog/unitOfWork.html) that stores and tracks all the objects in the model. As a Unit Of WorkDbContext lets you add an object for tracking, and then we set the EntityState parameter of the object so that DbContext can perform the correct database operation (INSERT, UPDATE, or DELETE) when needed—that is, when calling the Save() or SaveAsync() methods. 

When defining your instance of DbContext, you added properties of the DbContext type for each entity you wanted your model to include. The DbContext is a special type of collection that is aware of the EntityState objects, and lets you control them with simple methods such as Add() or Remove().

EF Core scans the graph objects that are being pointed to by the object you add to it and automatically adds the referenced objects if needed.

Here is an example of how products are added in the GiveNTake application:

//ProductsController.cs
[HttpPost("")]
public async Task<IActionResult> AddNewProduct([FromBody] NewProductDTO newProduct)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Category category = GetProduct(newpProduct.Category, newProduct.Subcategory);
City city = GetCity(newProduct.City);
User owner = await _context.Users.FindAsync("[email protected]"),
var product = new Product()
{
owner = owner,
Category = category,
Title = newProduct.Name,
Description = newProduct.Description,
City = city,
PublishDate = DateTime.UtcNow
};
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(
nameof(GetProduct),
new { id = product.ProductId },
...);
}

The method does some validation checks and then fetches some related entities (we will see how to create entity relationships later in this chapter). Then, a new instance of the Product entity is created. At this stage, the object is detached from DbContext, which means EF Core doesn't know of its existence. The _context.Products.Add(product) call attaches the new product to DbContext so that it will be tracked. Since we used the Add() method, the entity state is now added, and therefore, the call to _context.SaveChangesAsync() generates an INSERT statement.

In RESTful APIs, when an action creates a new resource, it should return the 201 (Created) status code and a header with the URI to the new resource location. ASP.NET Core makes it easy to create the standard response by using the CreatedAtAction() method, which accepts the action name, parameters, and the response data to return.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.110.155