public class OfficeContext : DbContext
{
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
@"Data Source=192.168.31.215;User ID=hj;Password=hj123;Database=office;Integrated Security=false");
optionsBuilder.LogTo(Console.WriteLine);
}
[Table("Student")]
public class Student
{
[Column("PriKey")]
[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Timestamp]
[Column("VerCol")]
public virtual byte[] RowVersion { get; set; }
[Column("Name")]
public string Name { get; set; }
}
}
class Program
{
static void Main(string[] args)
{
using var context = new OfficeContext();
var a = context.Students.FirstOrDefault(x => x.Id == 1);
a.Name = "123";
var c = context.SaveChanges();
}
}
我在 var c = context.SaveChanges();
断点 然后在sqlserver里面执update [Student] set Name ='345' where PriKey =1
然后继续执行 应该正常引发异常Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException
但是实际调试的时候不一会触发 很困惑
你应该更新RowVersion 的值,EF才会检测到数据发生变化
@diudiu1: 我没设置 rowVersion 字段 按照我上述说的流程也会大概率触发同步异常、 如果是rowVersion字段我该更新成什么呢