Search code examples
c#asp.net-mvcentity-frameworkusermanager

An entity object cannot be referenced by multiple instances of IEntityChangeTracker. Wi


namespace BoatShop.Controllers
{
    public class ManagerController : Controller
    {
    ApplicationDbContext dbContext;
    public ManagerController()
    {
        dbContext = new ApplicationDbContext();
    }
    public ManagerController(ApplicationUserManager userManager)
    {
        UserManager = userManager;
    }
    private ApplicationUserManager _userManager;
    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    public ActionResult Index()
    {return View();}

    public ActionResult ViewBoats()
    {
        var allBoats = dbContext.Boats.Where(x => x.isArchived == false).ToList();
        return View(allBoats);
    }

    public ActionResult MakeOrder(int boatId)
    {
        OrderViewModel model = new OrderViewModel
        {
            boatId = boatId,
            boatName = dbContext.Boats.FirstOrDefault(x => x.Id == boatId).Name,
            ManagerName = User.Identity.Name,
            userList = dbContext.Users.ToList()
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult MakeOrder(OrderViewModel model)
    {
        model.Order.Boat = dbContext.Boats.FirstOrDefault(x=>x.Id==model.boatId);
        ApplicationUser seller = UserManager.FindById(User.Identity.GetUserId());
        ApplicationUser customer = UserManager.FindById(model.CustomerId);
        model.Order.SalePerson = seller;
        model.Order.Customer = customer;
        model.Order.CreationDate = DateTime.Now;
        var order = model.Order;
        dbContext.Orders.Add(order);
        dbContext.SaveChanges();
        return RedirectToAction("Index");
        }
    }
}

By trial-and-error i have found out that error is caused by

model.Order.SalePerson = seller; model.Order.Customer = customer;

those lines. I think i need to detach those out of usermanager somehow, but i have no clue how. How can i solve this problem? Thank you in advance.


Solution

  • It's because you are merging entities from 2 different instances of a DbContext.

    • The UserManager from which the seller and customer, has its own instance.
    • The dbContext = new ApplicationDbContext() in the constructor of the controller.

    You need to use the same instance. There are many ways to do this. One of them being dependency injection.

    Or, based on your code, I guess that you could just call:

    HttpContext.GetOwinContext().Get<ApplicationDbContext>();
    

    This will give you the same instance of the DbContext as the UserManager but I think you can't call it in the constructor. You will have to call this in the action function or create a property like the UserManager.