[英]ASP.NET MVC: How can I put the StartDate of a current record on the EndDate of an earlier record
我有一個進行約會的課程,約會的人只插入開始日期和時間,但結束日期必須等於下一個約會的開始日期。 我的困難在於確保以前的約會始終將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();
}
}
}
有幾種可能的解決方案,這可能取決於您的偏好,以便在應用程序代碼或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; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.