现在正在研究这个C#Entity Framework更新问题。也许你们中的一个人可以看到我所缺少的东西。
问题出在代码的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 :(得分:3)
删除对Attach
的调用,该调用已附加到上下文。