Getting some input from user and insert multiple table with Entity Framework

1 answer

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

All answers to this question, which has the identifier 60758043

The best answer:

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

Last questions

how do i remove the switch on my home screen?
how to edit the JS date and time to update atuomatically?
How to utilize data stored in a multidimensional array
Powermockito not mocking URL constructor in URI.toURL() method
Android Bluetooth LE Scanner only scans when phone's Location is turned on in some devices
docker wordpress container can't connect to mysql container
How can I declare a number in java that is more than 64-bits? [duplicate]
Optaplanner solutionClass entityCollectionProperty should never return null error when simple JSON object passed to controller
Anylogic, get the time a pedestrain is in a queue
How do I fix this syntax issue with my .flex file?
Optimizing query in PHP
How to find the highest number of a column and print two columns of that row in R?
Ideas on “Error: Type com.google.firebase.iid.zzav is referenced as an interface from com.google.firebase.messaging.zzd”?
JCIFS SmbFile.exists() and SmbFile.isDirectory() return false when it exists and I can listFiles()
PHP total order
Laravel booking system design
neural net - undefined column selected
How to indicate y axis does not start from 0 in ggplot?
Fragments in backStack
Spinner how to change the data