0

I'm using Entity Framework Core database first (2.2.6). There is an instead of insert trigger attached to the Car table in the SQL Server database.

This trigger generates an Id based on some business rules and this ID is then inserted in a column in the Car table. The thing is, that I am not able to see the generated Id after I call SaveChanges() on the context - but it is present in the database. It is possible to see the generated Id if I create a new context, but I don´t feel this is a good solution.

So my question is, is it possible to reset (or something similar) the context instead of creating a new?

public ActionResult PostCar([FromBody]Car car)
{
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
                   
        context.Cars.Add(car); 
        context.SaveChanges();

        // var carWithNewId = context.Cars.Find(car.CarId) <-- The new id is not present

        Car carToReturn;

        using (var newContext = CreateContext())
        {
            carToReturn = newContext.Cars.Find(car.CarId);
        }

        return Ok(carToReturn.GeneratedId);
}

private CarContext CreateContext()
{
        var connectionstring = config.GetConnectionString("CarDbConnection");
        var optionsBuilder = new DbContextOptionsBuilder<CarContext>();
        optionsBuilder.UseSqlServer(connectionstring);
        return new CarContext(optionsBuilder.Options);
}
2

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.