我正在尝试使用用户存储库服务更新用户。我仍在使用 IdentityUser
,只是将其修改为使用 int
作为主键而不是 string/guid。
一切正常,直到我的 Update
抛出异常。
所以这是我在 BaseRepository
类中的更新方法:
public virtual void Update(T entity)
{
EntityEntry dbEntityEntry = _context.Entry<T>(entity);
dbEntityEntry.State = EntityState.Modified;
}
public virtual void Commit()
{
_context.SaveChanges();
}
调用本身:
[HttpPost]
[Route("home/account/edit")]
public ActionResult Edit(User user)
{
if (!ModelState.IsValid)
return View(user);
string id = _userManager.GetUserId(User);
user.Id = id.To<int>();
_userService.Update(user);
_userService.Commit();
return RedirectToAction("Index");
}
(我觉得没什么特别的)
所以现在,当它在 Commit
中保存我的更改时,它会抛出一个异常:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.
我想,好吧,我检查了分析器,不会那么棘手。 Profiler 向我展示了 Entity Framework 发送给他的声明:
exec sp_executesql N'SET NOCOUNT ON;
UPDATE [AspNetUsers] SET [AccessFailedCount] = @p0, [Birthday] = @p1, [ConcurrencyStamp] = @p2, [Email] = @p3, [EmailConfirmed] = @p4, [FirstName] = @p5, [Language] = @p6, [LastName] = @p7, [LockoutEnabled] = @p8, [LockoutEnd] = @p9, [MiddleName] = @p10, [NormalizedEmail] = @p11, [NormalizedUserName] = @p12, [PasswordHash] = @p13, [PhoneNumber] = @p14, [PhoneNumberConfirmed] = @p15, [SecurityStamp] = @p16, [TwoFactorEnabled] = @p17, [UserName] = @p18, [VerificationToken] = @p19
WHERE [Id] = @p20 AND [ConcurrencyStamp] = @p21;
SELECT @@ROWCOUNT;
',N'@p20 int,@p0 int,@p1 datetime2(7),@p2 nvarchar(4000),@p21 nvarchar(4000),@p3 nvarchar(256),@p4 bit,@p5 nvarchar(4000),@p6 nvarchar(4000),@p7 nvarchar(4000),@p8 bit,@p9 nvarchar(4000),@p10 nvarchar(4000),@p11 nvarchar(256),@p12 nvarchar(256),@p13 nvarchar(4000),@p14 nvarchar(4000),@p15 bit,@p16 nvarchar(4000),@p17 bit,@p18 nvarchar(256),@p19 nvarchar(4000)',@p20=1,@p0=0,@p1='1991-06-10 00:00:00',@p2=N'24fe11c5-a831-45ce-8960-16aa78b280df',@p21=N'24fe11c5-a831-45ce-8960-16aa78b280df',@p3=N'my@email.ch',@p4=0,@p5=N'Matthias',@p6=N'de-DE',@p7=N'Burger',@p8=0,@p9=NULL,@p10=NULL,@p11=NULL,@p12=NULL,@p13=NULL,@p14=NULL,@p15=0,@p16=NULL,@p17=0,@p18=NULL,@p19=NULL;
所以,[ConcurrencyStamp] = @p21
和 @p21=N'24fe11c5-a831-45ce-8960-16aa78b280df'
检查了我对该用户的记录...
ConcurrencyStamp
是 22fa7d03-1382-4eee-8c17-878253fdf1c4
所以我的问题是:
ConcurrencyStamp
是什么?- 为什么 Entity Framework 会过滤它?他得到了我的用户 ID。这还不够吗?
- 为什么用户对象有另一个
ConcurrencyStamp
而不是数据库中的对象?当 Entity Framework 要为其过滤时,它们不应该相同吗? - 有人有想法吗?我该如何/应该如何修复它?还是我做错了什么?
更新:
模型(现在也是 View 模型):
public class User : IdentityUser<int>, IEntity
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public DateTime Birthday { get; set; }
public string Language { get; set; }
public ICollection<MailBox> MailBoxes { get; set; } = new List<MailBox>();
public string VerificationToken { get; set; }
}
最佳答案
ConcurrencyStamp
用于防止两个人在不知道彼此的更改的情况下对同一用户进行两个不同的更改。
/// <summary>
/// A random value that must change whenever a user is persisted to the store
/// </summary>
public virtual string ConcurrencyStamp { get; set; } = Guid.NewGuid().ToString();
原则上,这应该在创建用户时分配一次,并且(我假设)应该有一种机制,如数据库中的触发器,只要数据库中的条目更新,就会导致值发生变化。
来自 this answer :
If you look at the implementation of IdentityDbContext in the OnModelCreating() method, you'll find:
builder.Entity<TUser>(b => { .... b.Property(u => u.ConcurrencyStamp).IsConcurrencyToken(); ....
所以 Entity Framework 意识到这应该被视为并发 token 。它会检查属性的值以及 ID,以确保如果自从该用户对象从数据库中加载后用户已更改,则更新会失败。
至于为什么值不一样,这可能是您必须通过调试弄清楚的事情。以下是您可能会检查的一些理论:
- 也许用户对象在加载后真的发生了变化?如果用户对象使用其原始值加载两次,然后独立更改两次,那么就会发生这种情况。
- 也许您正在根据传递到 Web 请求中的值构建用户对象,但您并没有根据从数据库中提取它时存在的值映射 ConcurrencyStamp token ,因此它会随机保留-首次构建时获得的生成的 GUID?
关于c# - Entity Framework : update user fails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40207663/