2015-01-27 100 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);

和它的作品。

感謝您的幫助和靈感。

Ç

相關問題