1

I want to add some information into my database. The question is how can I post my inputs for 3 table at the same time? My tables are below. Let me clear that.

I have teachers and working hours and working days. I want that firstly I select the teacher name from dropdownlist,then select the day from dropdownlist and write working hours for example "09:00 - 17:00". After that I submit these information I expectation is that seeing all these information can be added into database seperately and relationally.

Sample scenario: John Reese     Friday   09:00-17:00

                 Harold Finch   Monday   11:00-15:00

I am able to pull the teacher's names from database but at the same time in the same page I want to see that day's names. After all these selecetions as I mentioned above, I wanna add all these informations.

My Databese Scheme

My create controller

public ActionResult Create()
        {
            var myTeacherList = (from teacher in db.Teachers.ToList()
                select new SelectListItem
                {
                    Text = teacher.Firstname + teacher.Lastname,
                    Value = teacher.Id.ToString(),
                }).ToList();
            var myDayNameList = (from day in db.WeekDays.ToList()
                select new SelectListItem
                {
                    Text = day.Name,
                    Value = day.Id.ToString(),
                }).ToList();


            ViewBag.TeacherId = myTeacherList;
            ViewBag.DayId = myDayNameList;
            return View();
        }

My Create Controller

<div class="form-horizontal">
    <h4>Appointment</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.TeacherId, "Teacher Name", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m=>m.Teacher.Id,(List<SelectListItem>)ViewBag.TeacherId, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.TeacherId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Hours,"Working Hour", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Hours, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Hours, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

MSSQL Diagram

Teacher.cs


namespace LanguageSchool.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Teacher
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Teacher()
        {
            this.Appointments = new HashSet<Appointment>();
            this.Classes = new HashSet<Class>();
            this.Languages = new HashSet<Language>();
        }

        public int Id { get; set; }
        public string Description { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public System.DateTime DateOfStart { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

        public virtual ICollection<Appointment> Appointments { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

        public virtual ICollection<Class> Classes { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

        public virtual ICollection<Language> Languages { get; set; }
    }
}

Appointment.cs


namespace LanguageSchool.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Appointment
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]

        public Appointment()
        {
            this.WeekDays = new HashSet<WeekDay>();
        }

        public int Id { get; set; }
        public int TeacherId { get; set; }
        public string Hours { get; set; }

        public virtual Teacher Teacher { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

        public virtual ICollection<WeekDay> WeekDays { get; set; }
    }
}

WeekDay.cs


namespace LanguageSchool.Models
{
    using System;
    using System.Collections.Generic;

    public partial class WeekDay
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]

        public WeekDay()
        {
            this.Class_WeekDay = new HashSet<Class_WeekDay>();
            this.Appointments = new HashSet<Appointment>();
        }

        public int Id { get; set; }
        public string Name { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

        public virtual ICollection<Class_WeekDay> Class_WeekDay { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

        public virtual ICollection<Appointment> Appointments { get; set; }
    }
}

16
  • To clarify, you want to save to multiple tables at the same time and also save multiple records at the same time? Commented Mar 19, 2020 at 14:37
  • 1
    Yes, I actually want that I select a teacher and a day via dropdownlistfor and enter the working hour so that add the all these information into database.Ex: I select Teacher John and the day wednesday and enter the 09:00-15:00. after this process, I expec to see all these informations can be addedinto database relationally Commented Mar 19, 2020 at 15:03
  • 1
    Sure, I edited.@JerdineSabio Commented Mar 19, 2020 at 15:42
  • 1
    @JerdineSabio I will be working on your answer and I will reply. Thanks for now. I appreciate you. :))) Commented Mar 19, 2020 at 16:22
  • 1
    Yeah. The problem was in my relations between tables as you mentioned. Commented Mar 19, 2020 at 22:05

1 Answer 1

1

We need to make a ViewModel that contains all those properties so that the moment we do a POST request, they are all bound and we could access them for saving.

  1. But first we need to modify your models and insert a class for the many to many table.

We need to remove Weekday from Appointments and Appointments from Weekday.

Then replace them with AppointmentWeekday. Be sure to run Migrations/Update-Database after this first step.

public class Appointment{
   ...
   // REMOVE public virtual ICollection<WeekDay> WeekDays { get; set; }

   // Add this
   public virtual ICollection<AppointmentWeekday> AppointmentWeekdays {get;set;}
}

public class Weekday{
   ...
   // REMOVE public virtual ICollection<Appointment> Appointments { get; set; }

   // Add this
   public virtual List<AppointmentWeekday> AppointmentWeekdays {get;set;}
}

// Add this
public class AppointmentWeekday{
   public int AppointmentId {get;set;}
   [ForeignKey("AppointmentId")]
   public virtual Appointment Appointment {get;set;}

   public int WeekdayId {get;set;}
   [ForeignKey("WeekdayId")]
   public virtual Weekday Weekday {get;set;}
}
  1. Make the View Model with the necessary properties, I named it TeacherAppointmentViewModel.
public class TeacherAppointmentViewModel{
   public int TeacherId {get;set;}
   public int DayId {get;set;}
   public string Hours {get;set;}
}
  1. Instantiate this in your controller and pass it to the view.
public ActionResult Create()
{
   var myTeacherList = (from teacher in db.Teachers.ToList()
   select new SelectListItem
   {
      Text = teacher.Firstname + teacher.Lastname,
      Value = teacher.Id.ToString(),
   }).ToList();

   var myDayNameList = (from day in db.WeekDays.ToList()
   select new SelectListItem
   {
      Text = day.Name,
      Value = day.Id.ToString(),
   }).ToList();

   ViewBag.TeacherId = myTeacherList;
   ViewBag.DayId = myDayNameList;

   // instantiate
   TeacherAppointmentViewModel tvm = new TeacherAppointmentViewModel();

   // pass to the view
   return View(tvm);
}
  1. Make your view use TeacherAppointmentViewModel.
@model TeacherAppointmentViewModel
  1. Edit view, use the code below.
<div class="form-horizontal">
    <h4>Appointment</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.TeacherId, "Teacher Name", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m=>m.TeacherId,(List<SelectListItem>)ViewBag.TeacherId, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.TeacherId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.WeekdayId, "Day", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m=>m.WeekdayId,(List<SelectListItem>)ViewBag.WeekdayId, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.WeekdayId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Hours,"Working Hour", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Hours, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Hours, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
  1. Use controller action below, we need to assign the properties to Appointment and AppointmentWeekday then add to the db;
[HttpPost]
public ActionResult Create(TeacherAppointmentViewModel tvm){

   // create appointment
   Appointment a = new Appointment();

   // assign teacher id and hours from viewmodel
   a.TeacherId = tvm.TeacherId;
   a.Hours = tvm.Hours;

   // save appointment
   db.Appointments.Add(a);
   db.SaveChanges();

   // create appointmentweekday
   AppointmentWeekday aw = new AppointmentWeekday();

   // assign properties
   // since we've saved the appointment, we could use a.AppointmentId

   aw.WeekdayId = tvm.WeekdayId;
   aw.AppointmentId = a.AppointmentId; // appointment from earlier

   // save appointmentweekday
   db.AppointmentWeekdays.Add(aw);
   db.SaveChanges();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.