2013-07-25 232 views
1

現在正在處理此C#實體框架更新問題。也許你們中的一個可以看到我失蹤的東西。C#實體框架更新SaveChanges()不更新數據庫條目

問題出在代碼的userEntry部分。我已經追蹤並確保userEntry確實填充了我打算更新的信息。當調用entities.SaveChanges();時,記錄不會在數據庫中更新。

  int userId; 
      using (Entities entities = new Entities()) 
      { 
       MSIFeedStoreData feedStoreEntry = entities.MSIFeedStoreDatas 
        .FirstOrDefault((d) => d.Alias == user.Alias); 

       if (Object.ReferenceEquals(feedStoreEntry, null)) 
       { 
        throw new ArgumentException("The user's alias could not be located in the feed store. The user cannot be added at this time."); 
       } 

       int feedStorePersonnelIdValue; 
       if (Int32.TryParse(feedStoreEntry.PersonellID, out feedStorePersonnelIdValue)) 
       { 
        user.EmployeeId = feedStorePersonnelIdValue; 
       } 
       else 
       { 
        throw new ApplicationException("DATABASE BUG CHECK: An entry was found in the feed store for this user but the personnel ID could not be parsed."); 
       } 

       MSIUser userEntry = entities.MSIUsers 
        .FirstOrDefault((u) => u.EmployeeID == feedStorePersonnelIdValue); 

       if (Object.ReferenceEquals(userEntry, null)) 
       { 
        userEntry = Mapper.Map<MSIUser>(user); 
        userEntry = entities.MSIUsers.Add(userEntry); 
       } 
       else 
       { 
        Mapper.DynamicMap<User, MSIUser>(user, userEntry); 
        entities.MSIUsers.Attach(userEntry); 
       } 

       userId = userEntry.MSIUser_ID; 
       entities.SaveChanges(); 
      } 

      return userId; 
     } 
+0

你沒有改變任何東西。你的預期結果是什麼? –

+0

'Object.ReferenceEquals(feedStoreEntry,null)'更容易閱讀爲'feedStoreEntry == null'並且執行相同的操作。 –

+0

變化在這裏: else { Mapper.DynamicMap (user,userEntry); entities.MSIUsers.Attach(userEntry); } 有通過ajax PUT調用傳入的用戶條目。然後通過Mapper.DynamicMap將用戶映射到userEntry <用戶,MSIUser>(user,userEntry);我已通過調試進行驗證,確實發生了這種情況。 –

回答

2

刪除對Attach的調用,該調用已附加到上下文中。

+0

編輯以反映評論 –

+0

記得原始問題是什麼。 'MSIUser userEntry = entities.MSIUsers .FirstOrDefault((U)=> u.EmployeeID == feedStorePersonnelIdValue);' 最初被寫爲 'MSIUser userEntry = entities.MSIUsers .AsNoTracking() .FirstOrDefault ((u)=> u.EmployeeID == feedStorePersonnelIdValue);' –

相關問題