我搜索网站上的答案,但我没有找到一个。 我有以下问题...
我想在数据库中更新多条记录如下:
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 */
}
当我更新我的错误:
“DuplicateKeyException” 在 “JitemsTable.AttachAll(Jitem.Where(I => i.Id = 0)!);”。
如何正确地更新数据?
地址:剃须刀更新形式:
@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);
}
数据控制器保存(POST):在
[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);
}