Hello,
I have two models: Machine and Devices.
The relation between them is: A Machine has a collection of Devices.
How the PostAction should work:
When the user creates a new Machine, he will also declare the number of Devices that Machine has.
This way, if 3 devices are declared for a Machine, 3 registers must be saved on the Devices model.
The Code:
[HttpPost, ActionName("CreateEdit")] [ValidateAntiForgeryToken] public async Task<IActionResult> CreateEditPost(int? id, [Bind("TypeID,BrandID,SupplierID,StoreID,MchName,NumDevices,FechaCompra,CostoMaq,MachineStatus")]Machine model, [Bind("Id,DeviceName")]Device devicemodel) { if (id == null) { return NotFound(); } if (ModelState.IsValid) { if (id == 0) { _context.Add(model); for (var items = 0; items < model.NumDevices; items++) { var contador = items + 1; string devicename = model.MchName + "-" + contador.ToString(); devicemodel.DeviceName = devicename; _context.Add(devicemodel); await _context.SaveChangesAsync(); } await _context.SaveChangesAsync(); return RedirectToAction("Index"); } } return RedirectToAction("Index"); }
The problem:
When indicating, for example, 2 devices, here is what the debug is showing:
As shown, in the first attempt the DeviceID is 0. In the second attempt is 1006. This DeviceID is autogenerated.
At this point the application interrups claiming:
SqlException: Cannot insert explicit value for identity column in table 'Device' when IDENTITY_INSERT is set to OFF.
I believe this is happening because it's trying to write a zero on an Key field (DeviceID).
But also, it's saving one register on the database:
But it's saving a combination of the two attempts: (1) The DeviceName from attempt 1, (2) The DeviceID from attempt 2.
Can someone explain why in the first attempt the DeviceID is zero? How can this be fixed? And why is it saving the mix of both attempts?
Thanks in advance.