I'm new to Entity frameworks and got some questions. I've got an EFcore project where there needs to be a database around users, with roles, groups,..
First I had Razor CRUD pages where everything worked. I could add, update and delete users, roles, groups,... But along the way I realised that I rahter needed a SwaggerUI so I could use that API for an other frontend project.
So I changed the razor pages to Swagger and for some reason the database doesn't change when I Update, delete or post something. Without any warnings. I even get succes codes back as feedback. But the action doesn't really go through. (When I delete, it says deteled but record is still the same. Same with Update and with a post, it says that the creation succeeded but the new record is not in my database.
I can view all records with Get & specific Records with Get:ID so I'm kind of lost why my update, post or delete action don't work.
I'm kind of new in this area so any feedback is much appreciated. Thanks in advance.
Try to update/delete/post a record in db. Always gives
UserController : ( this worked with the Razor pages but not with the swagger page)
[HttpDelete("{id}")]
public ActionResult<User> Delete(int id)
{
var user = _userRepo.Get(id);
if(user != null)
{
_userRepo.Delete(id);Console.WriteLine("is deleted.");
}
else
{
return NotFound();
}
return NoContent();
}
[HttpPost()]
public IActionResult Add([FromBody] UserCreateViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var newUser = new User
{
FirstName = model.FirstName,
LastName = model.LastName,
Email = model.Email,
Platform = model.Platform,
Is_enabled = model.Is_enabled,
};
Console.WriteLine(newUser);
_userRepo.Add(newUser);
return CreatedAtAction(nameof(Get), new { newUser.Id }, newUser);
}
Note: The Console.WriteLine("is deleted.");
does run and is shown in the console. But it doesn't delete the record.
CodePudding user response:
In Entity Framework, the SaveChanges() method internally creates a transaction and wraps all INSERT, UPDATE and DELETE operations under it. Multiple SaveChanges() calls, create separate transactions, perform CRUD operations and then commit each transaction.