我有那段代码:
public class BaseClass{
[ConcurrencyCheck]
[Timestamp]
public byte[] RowVersion { get; set; }
}
public class User : BaseClass
{
public string UserName { get; set; }
}
public class Context : DbContext{
public DbSet<User> Users { get; set; }
...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Property(b => b.RowVersion)
.ValueGeneratedOnAddOrUpdate()
.IsConcurrencyToken();//It should not be necessary because I already specified in annotation
}
public override int SaveChanges()
{
var changes = ChangeTracker.Entries<BaseClass>().Where(p => p.State == EntityState.Modified).Select(u => u.Entity);
foreach (var change in changes)
{
Entry(change).Property(u => u.RowVersion).OriginalValue = new byte[] { 0, 0, 0, 0, 0, 0, 0, 120 };
}
return base.SaveChanges();
}
}
public class UserBusiness
{
public void Update(User user)
{
using(var ctx=new Context())
{
var editedUser=ctx.Set<User>().Where(u => u.Id == user.Id).FirstOrDefault();
editedUser.RowVersion = new byte[] { 0, 0, 0, 0, 0, 0, 0, 120 };
ctx.SaveChanges();
}
}
}
我希望在db中发现RowVersion已更改,但是相同。 editedUser.RowVersion被更改,更改跟踪器检测到更改,但在调用SaveChanges()之后,在数据库中rowVersion具有相同的初始值。