我有一个约会的课程,约会的人只插入开始日期和时间,但结束日期必须等于下一个约会的开始日期。我的困难在于确保以前的约会始终将EndDate接收为当前约会的StartDate
public class InfoAppointments : Entity
{
public bool Active { get; set; }
public bool Excluded { get; set; }
public string Status { get; set; }
public string Observation{ get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
编辑
我的存储库:
public class InfoAppointmentsRepository : Repository<InfoAppointments>, IAppointmentsRepository
{
public InfoAppointmentsRepository(RveContext rveContext) : base(rveContext)
{
}
public InfoAppointments FindByName(string name)
{
return Search(c => c.Name== name).FirstOrDefault();
}
public InfoAppointments FindByStatus()
{
throw new NotImplementedException();
}
public override void Remove(Guid id)
{
throw new NotImplementedException();
}
}
}
答案 0 :(得分:0)
对此有几种可能的解决方案,这可能取决于您在应用程序代码或SQL中(例如作为触发器)添加这种业务逻辑的偏好。我个人建议使用前者,因为此要求可能会随着时间的推移而发展,并且可能会影响业务逻辑的其他组件。
我做了一些假设:1)您正在使用Entity Framework,并且2)约会没有重叠,并且EndDate是唯一的。在这种情况下,您可以使用与以下类似的逻辑来实现此功能:
public class AppointmentService
{
private readonly MyContext _db;
public AppointmentService(MyContext db) => _db = db;
public void AddAppointment(InfoAppointments appointment)
{
// Update the previous appointment's end date
var previousAppointment = _db.Appointments
.OrderByDescending(e => e.EndDate)
.FirstOrDefault();
if (previousAppointment != null)
{
previousAppointment.EndDate = appointment.StartDate;
}
// Add the new appointment
_db.Appointments.Add(appointment);
_db.SaveChanges();
}
}
另一个评论:根据您的解释,看来EndDate应该默认为null,但是您使用了非null类型。我将其更改为以下内容:
public DateTime? EndDate { get; set; }