Linq To Sql使用AttachAll。 DuplicateKeyException

时间:2012-11-11 11:03:49

标签: c# sql-server asp.net-mvc entity-framework linq-to-sql

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

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

  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 =&gt; i.Id!= 0));”中的

“DuplicateKeyException”。

如何正确更新数据?

ADD: 剃刀更新表格:

@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);
    }

1 个答案:

答案 0 :(得分: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();