简体   繁体   中英

ASP.NET - Binding a Model multiple times

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 Device 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.

From what I can tell in your code, your loop is going through the number of devices that it thinks it has based off of the auto-bound number of devices in the Machine model, which I assume there is a hand-entered value for on your MVC form.

For each "Device" it has, you are literally trying to tell Entity Framework to add the same object (after it has its properties modified) and save it to the database. After the first "SaveChanges" call, the device's Id column will be updated to the ID that the database assigned to it. If you then try to add that to the DBContext again , it will try to create a NEW device with the SAME id, which is illegal unless, as it says, IDENTITY_INSERT is set to ON. Even it that setting was ON, it would be illegal because of the likely unique-ness constraint.

So, the first thing, is that it's a better practice to have DISCONNECTED models, and then a data layer which converts those model to actual entities and inserts those into the DB. But, barring that, something like this, which creates a new Device each time around, would work better:

        if (id == 0)
        {
            _context.Add(model);
            for (var items = 0; items < model.NumDevices; items++)
            {
                var contador = items + 1;
                string devicename = model.MchName + "-" + contador.ToString();
                var devNew = new Device();
                devNew.DeviceName = devicename;
                _context.Add(devNew);
                await _context.SaveChangesAsync();
            }
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }

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