更新Entity Framework Core中的多对多关系

时间:2019-01-09 00:26:53

标签: c# asp.net-core entity-framework-core

我正在尝试使用 Entity Framework Core ASP.NET Core MVC 控制器中更新many-to-many关系。我设法使此工作能够添加到关系中,但没有更新(如果我只是打开/保存实体,则会导致重复的键错误)。

在有效地更新/插入新关系之前,如何从数据库中删除关系?

public async Task<IActionResult> Edit(int id, [Bind("Id,Name,SalesClerkIds")] Plant plant)
{
        if (id != plant.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                plant.SalesClerks = new List<PlantSalesClerk>();

                if (plant.SalesClerkIds != null)
                {
                    foreach (var scId in plant.SalesClerkIds)
                    {
                        plant.SalesClerks.Add(new PlantSalesClerk()
                        {
                            Plant = plant,
                            User = _context.Users.FirstOrDefault(u => u.Id == scId)
                        });
                    }
                }

                _context.Update(plant);

                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PlantExists(plant.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }

        return View(plant);
  }

1 个答案:

答案 0 :(得分:0)

编写您的import java.awt.BorderLayout; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class Checklist extends JFrame { private JLabel description; private JButton send; private JTextField text[]; private JCheckBox cb[]; public Checklist() { setTitle("Activities"); setSize(400,400); setupWidgets(); setVisible(true); } private void setupWidgets() { JPanel pn_center = new JPanel(new GridLayout(10,1)); JPanel pn_west = new JPanel(new GridLayout(10,1)); description = new JLabel("List your activities and uncheck the irrelevant ones"); send = new JButton("Send Checklist"); for (int i=0; i<10; i++) { text[i] = new JTextField(); cb[i] = new JCheckBox(); } add(description, BorderLayout.NORTH); add(pn_center, BorderLayout.CENTER); add(pn_west, BorderLayout.WEST); add(send, BorderLayout.SOUTH); for (int i=0; i<10; i++){ pn_center.add(text[i]); pn_west.add(cb[i]); } } public static void main(String[] args) { new Checklist(); } } 发布方法,如下所示:

Edit

注意:我没有看到您的模型类和编辑视图。我已经根据您的代码假设了一切。因此可能需要进行一些调整,但这是在EF核心中使用子代更新模型的概念。