現在正在處理此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;
}
你沒有改變任何東西。你的預期結果是什麼? –
'Object.ReferenceEquals(feedStoreEntry,null)'更容易閱讀爲'feedStoreEntry == null'並且執行相同的操作。 –
變化在這裏: else { Mapper.DynamicMap(user,userEntry); entities.MSIUsers.Attach(userEntry); } 有通過ajax PUT調用傳入的用戶條目。然後通過Mapper.DynamicMap將用戶映射到userEntry <用戶,MSIUser>(user,userEntry);我已通過調試進行驗證,確實發生了這種情況。 –