2015-01-27 75 views
0

对不起,如果主题不准确,但基本上在提交表单之前,我想比较模型的外键的先前值。在表单提交之前检查值在POST控制器中

我的模式是:

public class Booking 
{ 
    public int ID { get; set; } 

    [ForeignKey("Store")] 
    public int StoreID { get; set; } 
    public virtual Store Store { get; set; } 

    public string BookedBy { get; set; } 
    public DateTime? DateBooked { get; set; } 
    public string Description { get; set; } 
    public DateTime FromDate { get; set; } 
    public DateTime ToDate { get; set; } 

    public string Status { get; set; } 
} 

编辑在编辑观点预订并提交后,我要检查,如果STOREID已被修改,这样我就可以执行所需的操作。

我正在创建一个预订为oldBooking的实例,然后将StoreIDbooking.StoreID进行比较,然后在View中传回,但是在保存编辑后的窗体时创建了附加错误。

有什么建议吗?

编辑27/1/15:

public ActionResult Edit([Bind(Include = "ID,StoreID,BookedBy,DateBooked,Agreement,Description,FromDate,ToDate")] Booking booking, string returnURL) 
{ 
    if (ModelState.IsValid) 
    { 
    Booking oldBooking = db.Bookings.Find(booking.ID); 
    int prevStoreID = oldBooking.StoreID; 
    db.Entry(booking).State = EntityState.Modified; 
    db.SaveChanges(); 
    if(prevStoreID == booking.StoreID) 
    { 
     sendStoreChangeEmail(prevStoreID, booking.StoreID); 
    } 
    return RedirectToAction("Index", "Home", null); 
    } 
    ViewBag.StoreID = new SelectList(db.Stores, "ID", "ID", booking.StoreID); 
    return View(booking); 
} 

当尝试更新数据库进入状态,我得到这个错误:

"Attaching an entity of type 'uatlab2.Models.Booking' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate."

+0

在POST方法,只是从数据库中获取的原始'Booking'和比较'StoreID'值 – 2015-01-27 01:46:19

+0

这就是我做的: 预订oldBooking = db.Bookings.Find(booking.ID) ; int prevStoreID = oldBooking.StoreID; db.Entry(booking).State = EntityState.Modified; db.SaveChanges();如果(prevStoreID == booking.StoreID) sendStoreChangeEmail(prevStoreID,bookingStoreID);如果(prevStoreID == booking.StoreID) sendStoreChangeEmail(prevStoreID,bookingStoreID); 但是当我尝试保存修改后的预订时,它给出了以下错误: “附加类型为”uatlab2.Models.Booking“的实体失败,因为另一个相同类型的实体已具有相同的主键值。 任何想法? – 2015-01-27 10:59:13

+0

请编辑你的问题与额外的代码(太难以阅读评论,尤其是当你不格式化!) – 2015-01-27 11:02:20

回答

0

阅读一对夫妇的其他职位和谷歌搜索“分离”后,我读这篇文章: ASP MVC How to update DB entry with collections field

和我有prevStoreID做到这一点后: ((IObjectContextAdapter)DB).ObjectContext.Detach( oldBooking);

和它的作品。

感谢您的帮助和灵感。

Ç