我正在尝试使用 EFCore 3.1.
但是我的修改没有被保存到数据库中,所以经过进一步调查我发现在我从上下文中拉出我的实体后,它的状态是 DETACHED
而不是 ATTACHED
,
所以这就是没有保存更改的原因,因为它们首先没有被跟踪。
我无法弄清楚为什么会发生这种情况,我确保在获取实体时没有添加 AsNoTracking()
。
这是我的类和方法:
public class UserSettingsDataAccess : IUserSettingsDataAccess
private readonly NotificationDBContext _context;
private readonly IReminderDatesDataAccess _reminderDatesDataAccess;
public UserSettingsDataAccess(NotificationDBContext context, IReminderDatesDataAccess reminderDatesDataAccess)
{
_context = context;
_reminderDatesDataAccess = reminderDatesDataAccess;
}
public bool ToggleRemindersForAppointmentAsync(int appointment_id)
{
Appointments appointment = _appointmentDataAccess.GetByIdWithReminders(appointment_id);
if (appointment == null || appointment.Reminders == null)
return bool.Parse(null);
var x = _context.Entry(appointment).State;
appointment.Reminders.IsActive = !appointment.Reminders.IsActive;
var y = _context.Entry(appointment).State;
_context.SaveChanges();
var z = _context.Entry(appointment).State;
return appointment.Reminders.IsActive.Value;
}
//rest of code is omitted for brevity
}
这个使用另一种方法来获取约会,切换其提醒,保存更改并返回新的提醒状态。所有 x
,y
,z
变量都有 DETACHED
值。调试时
这是包含带来约会的方法的第二个类:
public class AppointmentDataAccess: IAppointmentDataAccess
{
private readonly NotificationDBContext _context;
public ReminderDatesDataAccess(NotificationDBContext context)
{
_context = context;
}
public Appointments GetByIdWithReminders(int appointment_id)
{
return _context.Appointments.Where(a => a.Id == appointment_id && a.DeletedAt == null)
.Include(a=>a.Reminders).FirstOrDefault();
}
}
Startup.cs
:
services.AddDbContext<NotificationDBContext>(options => options
.UseSqlServer(Configuration.GetConnectionString("Database"))
, ServiceLifetime.Transient,ServiceLifetime.Transient);
和IUserSettingsDataAccess
、IAppointmentDataAccess
只是接口。
谁能指出为什么会这样?以及如何解决它?它让我发疯了好几个小时。 TIA!