Получение некоторого ввода от пользователя и вставка нескольких таблиц с Entity Framework - PullRequest
1 голос
/ 19 марта 2020

Я хочу добавить информацию в свою базу данных. Вопрос в том, как я могу опубликовать свои данные для 3 таблиц одновременно? Мои таблицы ниже. Позвольте мне прояснить это.

У меня есть учителя, рабочее время и рабочие дни. Я хочу, чтобы сначала я выбрал имя учителя из выпадающего списка, затем выберите день из выпадающего списка и напишите рабочие часы, например, «09:00 - 17:00». После этого я предоставляю эту информацию, и я ожидаю, что увидев, что вся эта информация может быть добавлена ​​в базу данных отдельно и реляционно.

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

                 Harold Finch   Monday   11:00-15:00

Я могу вытащить имена учителей из базы данных, но в то же время в то же время страница, которую я хочу видеть имена того дня. После всех этих выборов, как я упоминал выше, я хочу добавить всю эту информацию.

My Databese Scheme

Мой контроллер создания

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

Мой Контроллер создания

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

1 Ответ

1 голос
/ 19 марта 2020

Нам нужно создать ViewModel, которая содержит все эти свойства, чтобы в момент выполнения запроса POST все они были связаны, и мы могли получить к ним доступ для сохранения.

  1. Но сначала нам нужно измените ваши модели и вставьте класс для таблицы «многие ко многим».

Нам нужно удалить Weekday из Appointments и Appointments из Weekday.

Тогда замените их на AppointmentWeekday. Обязательно запустите Migrations / Update-Database после этого первого шага.

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;}
}
Сделайте View Model с необходимыми свойствами, я назвал ее TeacherAppointmentViewModel.
public class TeacherAppointmentViewModel{
   public int TeacherId {get;set;}
   public int DayId {get;set;}
   public string Hours {get;set;}
}
Создайте это в вашем контроллере и передайте его в представление.
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);
}
Сделайте ваш вид использования TeacherAppointmentViewModel.
@model TeacherAppointmentViewModel
Изменить вид, используйте код ниже.
<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>
Используйте действие контроллера ниже, нам нужно присвоить свойства Appointment и AppointmentWeekday, затем добавить к БД;
[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();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...