0

I'm trying to save my model into a SQL database, but after calling the method CreateReservation, the database is still without data. I get no error.

public async Task CreateReservation(DateTime date, int _id, string name)
{
    ReservationModel reservationModel = new ReservationModel { Cas = date, Name = name, Id = _id,Room= await _roomModel.GetRoom(_id) };

    await _db.Reservations.AddAsync(reservationModel);
    _db.SaveChanges();
} 

Model

public class ReservationModel
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public DateTime Cas { get; set; }

    public RoomModel Room { get; set; }

    public ReservationModel()
    {
    }

    public ReservationModel(int id, string name, DateTime cas, RoomModel room)
    {
        Id = id;
        Name = name;
        Cas = cas;
        Room = room;
    }
}

Method is called from a controller:

[HttpPost]
[Route("Home/Room/Create_reservation")]
public IActionResult CreateReservation([Bind("Name")] ReservationModel reservationModel)
{
    _reservation.CreateReservation((DateTime)TempData["Date"], (int)TempData["Id"],reservationModel.Name);
    return RedirectToAction("Index");
}
8
  • how come you don't use await _db.SaveChangesAsync(); ? Commented Jul 16, 2022 at 16:48
  • I do i was just trying if it will not help if I will do it sync and forget to put it back. Commented Jul 16, 2022 at 16:50
  • You need to await all asynchronous calls, including CreateReservation. Awaiting it ensures that it completes - either successfully or with an exception. Without awaiting it, you can't be sure that it's finished. Don't forget to mark your action method as async and have it return Task<IActionResult> instead of IActionResult. Commented Jul 16, 2022 at 16:53
  • make it async all the way, or use CreateReservation(...).GetAwaiter().GetResults(); Commented Jul 16, 2022 at 16:56
  • @iSR5 Please don't advocate using .GetAwaiter().GetResult() unless there's a real reason to do so. There is no reason to do so in this case: action methods fully support async. Commented Jul 16, 2022 at 17:01

1 Answer 1

1

The problem was in action method. I had to add async await.

public async Task<IActionResult> CreateReservation([Bind("Name")] ReservationModel reservationModel)
    {
        await _reservation.CreateReservation(reservationModel,(DateTime)TempData["Date"], (int)TempData["Id"]);
        return RedirectToAction("Index");
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.