简体   繁体   中英

ASP.NET MVC Deleting row from one table after copying it to another table

I have a case where I am trying to Delete one item from a table but before doing that I want to copy it to another table.

Here is my Delete method:

public ActionResult Delete(int id, Car car)
    {
        try
        {
           using (BookCarDBEntities db = new BookCarDBEntities())
            {
                var carToDelete = db.Cars.FirstOrDefault(c => c.Id == id);
                var book = CreateNewBooking(carToDelete);
                db.Bookings.Add(book);

                db.Cars.Remove(carToDelete);

                db.SaveChanges();

                return View(book);
            }
        catch (Exception ex)
        {
            return View(ex + "error");
        }
    }

And here is a method which does the conversion from 'Car' table to 'Booking' table:

 private object CreateNewBooking(Car car)
    {
        var bookingCreated = new Booking
        {
            id = car.Id,
            model = car.model,
            make = car.make,
            price = car.price,
            location = car.location
        };

        return bookingCreated;
    }

The problem is that I get an error:

'System.InvalidOperationException': The entity type Booking is not part of the model for the current context.

How can I solve this?

You managed to fix the error (in the comments) but I'll post the solution here for others.

The error:

'System.InvalidOperationException': The entity type Booking is not part of the model for the current context.

can be caused for a couple of reasons.

  1. The entity has become detached or has somehow lost its reference within the entity framewowrk. This can be resolved by refreshing the entities. Go to the edmx file, right-click on the designer surface and selecting Update model from database . If that still fails, delete the entity (or all entities) in the designer and then update model from database.

  2. If the table/entity does not exist. In this case create the table/entity and update the entities.

  3. Then Rebuild after you have updated from database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM