Reputation: 115
I have that code:
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();
}
}
}
I expect to find RowVersion changed in db, but is the same. editedUser.RowVersion is changed, change tracker detect the change, but after SaveChanges() is called, in database rowVersion has the same initial value.
Upvotes: 2
Views: 371