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

冷暖自知 提交于 2020-01-05 05:46:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/53712157/asp-net-mvc-deleting-row-from-one-table-after-copying-it-to-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!