简体   繁体   中英

ASP.NET MVC: How can I put the StartDate of a current record on the EndDate of an earlier record

I have a class that makes appointments, the person making a appointments only inserts the start date and time, but the end date must be equal to the start date of the next appointments. My difficulty is in ensuring that the previous appointments always receives the EndDate as the StartDate of the current appointments

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; }  
}

EDIT

My Repository:

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();

    }

}

}

There are several possible solutions to this, and it may depend on your preference for adding this sort of business logic in your application code or in SQL (eg as a trigger). I would personally recommend the former, as this requirement may evolve over time, and may affect other components of your business logic.

I've made a few assumptions: 1) That you are using Entity Framework, and 2) Appointments don't overlap, and EndDate is unique. If that is the case, you could implement this functionality using similar logic to the following:

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();
    }
}

One other comment: based on your explanation, it appears that EndDate should default to null, but you've used a non-nullable type. I would change it to the following:

public DateTime? EndDate { get; set; }  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM