2017-06-02 48 views
0

我想更新實體對象記錄,但它不顯示異常但它不更新記錄。實體框架Linq更新數據不起作用

在objetct以前它包含空值issue_detail,之後用戶更新數據調用下面的方法

public Boolean bookReturnedUpdate(Issue_Detail issue) 
    { 

     BookController bookController = new BookController(); 
     int bookID = (int) issue.book_id; 
     Book_Detail book = bookController.findByBookID(bookID); 
     int noOfCopies = (int) book.no_of_copies; 

     book.no_of_copies = ++noOfCopies; 
     Console.Write("just before the update"); 
     bookController.updateBook(book); 

     Console.WriteLine("Issue ID" +issue.issue_id); 
     Boolean status = false; 
     try 
     { 
      using (var db = new ModelDB()) 
      { 



       DateTime issueD = (DateTime) issue.return_date; 
       Console.WriteLine("Details " + issueD); // here I can see the date is update and it contains the new date I have inserted 

       db.Entry(issue).State = EntityState.Modified; 

       db.Issue_Detail.Attach(issue); 

       db.SaveChanges(); // this returns 0 when I have checked wit h Console.WriteLine 

       status = true; 

      } 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Book return update error " + ex.InnerException); 
     } 
     return status; 
    } 

但更新完成後它仍然保留舊的零記錄,因爲它是。 enter image description here

謝謝。

我已經嘗試過db.SaveChanges()也沒有人若需要完整的資料庫,請檢查下面的鏈接Github上 https://github.com/ccmcwolf/LibraryManagementSystem

+0

你爲什麼要叫'db.Issue_Detail.Attach(發行);以後'db.Entry(問題).STATE = EntityState.Modified';'? – grek40

+0

我試着只是添加db.SaceChanges()它沒有工作,這就是爲什麼試圖添加也是 –

回答

1

你可以這樣說:

dbContext.Issue_Detail.Attach(issue); 
var entry = dbContext.Entry(issue); 
entry.State = EntityState.Modified; 
db.SaveChanges(); 
+0

它工作謝謝。 –

+0

@ChamithChathuka,很高興知道! –

0

如果要更新現有的記錄,最簡單的工作

方法是首先從數據庫檢索項目,然後更新值。

從代碼中的相關部分(以下未測試的代碼):

using (var db = new ModelDB()) 
{ 

    var entity = db.Issue_Detail.FirstOrDefault(i => i.issue_id == (int)issue.issue_id); 
    if (entity == null) 
    { 
     //handle error: 
     throw new Exception("Issue not found"); 
    } 
    //here we update the properties: 
    db.Entry(entity).CurrentValues.SetValues(issue); 
    db.SaveChanges(); 

    status = true; 
} 
+0

但問題是book_id不是Issue_detail表的主鍵,然後它返回一個錯誤異常,當我嘗試使用issue.issue_id(這是Issue_detail表的主要kiey) –

+0

更新我的代碼,請嘗試上面的代碼。 – JanR

1

我認爲這個問題是您db.Issue_Detail.Attach(issue);呼叫權限保存前...

DbSet.Attach

注在某些其他狀態中已處於上下文中的實體將其狀態設置爲未更改

這意味着您在設置後會丟失State = Modified