使用EF core 3.1的Net core 3.1项目的第一种方法:
services.AddDbContext<TestDBContext>(options =>
options.UseMySql(_configuration.GetConnectionString("TestDB"), mySqlOptions => mySqlOptions
.ServerVersion(new Version(8, 0, 20), ServerType.MySql)));
dbContext中只有一个实体
public partial class TestDBContext : DbContext
{
public DbSet<Patient> Patient { get; set; }
public TestDBContext()
{
}
public TestDBContext(DbContextOptions<TestDBContext> options)
: base(options)
{
}
}
然后在存储库层中,添加一个Patient,然后调用.SaveChangesAsync()方法,按预期方式工作,然后修改一个字段,并且ef在不调用.SaveChangesAsync()的情况下更新数据库中的该字段,为什么没有调用.SaveChangesAsync()进行更新吗?
public class PatientRepository : IPatientRepository {
private readonly TestContext _dbContext;
public PatientRepository (TestDBContext dbContext) => _dbContext = dbContext ??
throw new ArgumentNullException (nameof (dbContext));
/// <inheritdoc />
public async Task<Guid> CreatePatientAsync (Patient patient) {
_dbContext.Patient.Add(patient);
await _dbContext.SaveChangesAsync();
if(string.IsNullOrEmpty( patient.PatientId))
{
//This part is updated without savechanges, why ?
patient.PatientId = patient.PatientCode.ToString("D7");
}
return patient.Id;
}
}