1

我在网站上搜索了答案,但没有找到答案。我有以下问题...

我正在尝试更新数据库中的多条记录,如下所示:

  public void SaveJItem(List<DataForDespatcher> Jitem)
        {
             JitemsTable.InsertAllOnSubmit(Jitem.Where(i => i.Id ==0));
JitemsTable.AttachAll(Jitem.Where(i => i.Id != 0));
JitemsTable.Context.Refresh(RefreshMode.KeepCurrentValues, Jitem);
JitemsTable.Context.SubmitChanges(); 

        }

该表描述如下:

 [Table(Name = "tanks")] 
    public class DataForDespatcher
    {
        [Column(IsPrimaryKey = true, IsDbGenerated = true,AutoSync = AutoSync.OnInsert)]
        public int Id { get; set; }
    /*bla bla bla */
}

当我更新时,我收到错误:

“JitemsTable.AttachAll(Jitem.Where(i => i.Id != 0));”中的“DuplicateKeyException”。

如何正确更新数据?

添加:剃须刀更新表格:

@inherits WebViewPage<IEnumerable<DomainModel.Entities.DataForDespatcher>>
/*bla bla bla*/

数据控制器保存(获取):

public ViewResult EditForDispatcher(int group)
        {
            var list = DataRep.JItems.Where(x => x.group == group).Select(x => x);
            return View(list);
        }

数据控制器保存(发布):

 [HttpPost]
        public ActionResult EditForDispatcher(List<DataForDespatcher> Jitem, string addNewOperation, string sendParam, string operations)
        {
                if (ModelState.IsValid)
                {
 int group = DataRep.JItems.ToList().Max(x => x.group + 1);

                    if (Jitem.Any(x => x.group != 0))
                        foreach (var dataForDespatcher in Jitem)
                            dataForDespatcher.group = Jitem.Where(x=>x.group!=0).Select(x=>x.group).First(); 
                    else
                        foreach (var dataForDespatcher in Jitem)
                            dataForDespatcher.group = group; 
                    DataRep.SaveJItem(Jitem);
                }
         return View(Jitem);
    }
4

1 回答 1

0

我的意思是发生异常是因为您在 List 中有更新的项目和新的项目,并且列表中的第一个项目不是插入的项目。我认为,你必须这样做:

    JitemsTable.InsertAllOnSubmit(Jitem.Where(i => i.Id ==0));
    JitemsTable.AttachAll(Jitem.Where(i => i.Id != 0));
    JitemsTable.Context.Refresh(RefreshMode.KeepCurrentValues, Jitem);
    JitemsTable.Context.SubmitChanges(); 
于 2012-11-11T11:42:50.077 回答