我有这个代码:
var user = new User { UserName = "whatever", LastLoginOn = DateTime.UtcNow };
_baseRepository.Context.Users.Attach(user);
_baseRepository.Context.Entry(user).Property(p => p.LastLoginOn).IsModified = true;
_baseRepository.SaveChanges();
问题是我收到了这个错误:"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries."
当我使用 UserId 时,它可以工作,但是我必须往返数据库才能获取该 ID。有没有办法通过用户名进行查找?
编辑
为了解决这个问题,我已经这样做了:
_baseRepository.Context.Database.ExecuteSqlCommand(string.Format("UPDATE [dbo].[User] SET LastLoginDate = SYSUTCDATETIME() WHERE [UserName] = '{0}'", username));
但这不合适,很高兴知道真正的答案是什么。