Andrew
Andrew

Reputation: 2011

MVC3 Save Model multiple times

I need to be able to save the same model multiple times in with a for loop. My Action has two parameters, InventoryViewModel movie and int quantity. If the quantity is 3, for example, I need to save three copies to the database.

In my controller I have:

[HttpPost]
    public ActionResult addInventory(InventoryViewModel movie, int Quantity)
    {
        movie.Inventory.isAvail = true;
        if (ModelState.IsValid)
        {
            for (int i = 0; i < Quantity; i++)
            {
                inventoryRepository.save(movie.Inventory);
                movie = new InventoryViewModel();
            }
            return RedirectToAction("index");
        }
        return View("index", movie);
    }

I thought setting the movie = new InventoryViewModel would create a new instance of the movie, but it doesn't work. If I take that line out, it hits the else statement after it adds the first copy to the database. The CheckoutNum is the primary key of the table so I cannot set it to 0 in the for loop. I can't remember the exact error, but it's something about the primary key cannot be modified.

Repository:

public void save(Inventory movie)
    {
        if (movie.CheckoutNum == 0)
            db.Inventory.Add(movie);
        else
            db.Entry<Inventory>(movie).State = System.Data.EntityState.Modified;

        db.SaveChanges();
    }

Upvotes: 0

Views: 369

Answers (1)

von v.
von v.

Reputation: 17108

When you first saved your entity it is already flagged as "not new". So on succeeding calls it will do an update. What you should do is create a new instance of Inventory on each loop:

for (int i = 0; i < Quantity; i++)
{
    var entityToSave = new Inventory();
    // map the property values to save

    inventoryRepository.save(entityToSave);
}

Upvotes: 1

Related Questions