保存更新实体框架时出现MVC 3剃刀实体框架错误 [英] MVC 3 Razor Entity Framwork Error When Saving Update Entity Framework
问题描述
HI
我是MVC的新手,目前正在将MVC3与Entity Framwork一起使用.
我正在尝试编辑数据库中的记录,但是由于存在我无法修复的错误而无法进行.
以下是错误信息在执行此代码
HI
I am new to MVC, I am currently using MVC3 with Entity Framwork.
I am trying to Edit a record in my DB,but cannot due to an error that i cannot for the life of me fix.
Below is erro That is beeing thrown when excuting this lone of code
db.Tickets.Attach(ticket);
任何帮助将不胜感激.谢谢:)
具有相同键的对象已存在于ObjectStateManager中. ObjectStateManager无法使用相同的键跟踪多个对象.
Any assistance will be much appreciated. Thank you :)
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
[HttpPost]
public ActionResult Edit(Ticket ticket)
{
if (ModelState.IsValid)
{
Ticket ticket1 = db.Tickets.Single(t => t.TicketID == ticket.TicketID);
ticket.DateCreated = ticket1.DateCreated;
db.Tickets.Attach(ticket);
db.ObjectStateManager.ChangeObjectState(ticket, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
//ViewBag.CategoryType_CategoryTypeID = new SelectList(db.CategoryTypes, "CategoryTypeID", "CategoryTypeDesc", ticket.CategoryType_CategoryTypeID);
ViewBag.HighLevelCategory_HighLevelCategoryID = new SelectList(db.HighLevelCategories, "HighLevelCategoryID", "HighLevelCategoryDesc", ticket.HighLevelCategory_HighLevelCategoryID);
ViewBag.Priority_PriorityID = new SelectList(db.Priorities, "PriorityID", "PriorityDesc", ticket.Priority_PriorityID);
ViewBag.ServiceProvider_ServiceProviderID = new SelectList(db.ServiceProviders, "ServiceProviderID", "ServiceProviderName", ticket.ServiceProvider_ServiceProviderID);
ViewBag.Site_SiteID = new SelectList(db.Sites, "SiteID", "SiteName", ticket.Site_SiteID);
ViewBag.SubCategory_SubCategoryID = new SelectList(db.SubCategories, "SubCategoryID", "SubCategoryDesc", ticket.SubCategory_SubCategoryID);
ViewBag.Status_TicketStatusID = new SelectList(db.TicketStatus, "TicketStatusID", "TicketStatusDesc", ticket.Status_TicketStatusID);
return View(ticket);
}
推荐答案
错误表示它的意思.在将项目添加到集合之前,请搜索集合以确保其不存在.如果要进行批量插入,则必须跟踪插入的内容,就像保留代表键的字符串或整数列表一样简单.不要插入两次.如果这样做,则会出现此错误.
The error means what it says. Before you add an item to the collection, search the collection to make sure it''s not there. If you''re doing a bulk insert, you must keep track of what you inserted, which is as easy as keeping a list of strings or ints that represents the keys. Don''t insert something twice. If you do, you get this error.
克里斯蒂安
感谢您的回应.
删除
时
Hi Christian
thanks for the response.
When removing
Ticket ticket1 = db.Tickets.Single(t => t.TicketID == ticket.TicketID);
ticket.DateCreated = ticket1.DateCreated;
我在视图中添加了创建日期作为隐藏字段.
最初它返回为null.
i added date created to the view as a hidden field.
initially it was coming back as null.
@Html.HiddenFor(model => model.DateCreated)
这篇关于保存更新实体框架时出现MVC 3剃刀实体框架错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!