Use Linq to get details from a database so people can't create a new entity

Just learning C# and I'm developing a program from home.

I have an appointments entity in my application. I want to have it so someone can put their details down with a choice of rooms, dates and administrators (FK) at their disposal.

When they hit the button to create, I want the Linq Query to perform a search to see if all the criteria is available, i.e. that the appointment can be made. I'm just struggling with it at the moment.

Here is what I have:

 var currentBooking = db.Appointments
        .Where(b => b.AppointmentId == appointments.AppointmentId)
        .Select(b => (appointments.RoomType == b.RoomType && appointments.DateOfAppointment == b.DateOfAppointment && appointments.AdministrationId == b.AdministrationId))
        .FirstOrDefault();

            if (currentBooking)
            {
                throw new Exception("The Room is already out on that date.");
            }
            else
            {
                db.Appointments.Add(appointments);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

1 answer

  • answered 2018-01-11 20:20 Nkosi

    If based on what you said this is a new appointment then it should not have an id set as yet. Next you can simple query using Any to verify that the filter exists.

    var currentBooking = db.Appointments
        .Any(b => appointments.RoomType == b.RoomType 
            && appointments.DateOfAppointment == b.DateOfAppointment 
            && appointments.AdministrationId == b.AdministrationId);
    
    if (currentBooking) {
        throw new Exception("The Room is already out on that date.");
    } else {
        db.Appointments.Add(appointments);
        db.SaveChanges();
        return RedirectToAction("Index");
    }