在 Entity Framework Core 中的下拉菜单中关联外键

Associating foreign key on dropdown in Entity Framework Core

我正在构建一个简单的大学管理系统,其中有两个模型(现在)。以下是我的模型 类.

public class FacultyModel
{
    [Key] 
    public int s_no { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public string? file { get; set; }
    public string? hod { get; set; }
    public ICollection<ProgramModel> ProgramModels { get; set; }
}

public class ProgramModel
{
    [Key] 
    public int s_no { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public string? file { get; set; }
   
    public string type { get; set; }
    public string system { get; set; }
    public string? director { get; set; }
    public int sem_year { get; set; }
    [ForeignKey("fid")]
    public FacultyModel faculty { get; set; }  
    public int fid { get; set; }
}

我已经完成了教师的 CRUD 操作。现在,在插入程序(程序模型)时,我希望用户从下拉列表或 select 列表中 select 一位教员,selected 教员的密钥将设置在程序模型的外键。我被困在这个

下面是我的教员模型控制器

public class AdminFacultyController : Controller
{
    private readonly DataContext _context;

    public AdminFacultyController(DataContext context, IWebHostEnvironment webHostEnvironment)
    {
        _context = context;
        _webHostEnvironment = webHostEnvironment;
    }

    private readonly IWebHostEnvironment _webHostEnvironment;

    // GET
    public async Task<string> UploadImage(string folderpath, IFormFile file)
    {
        folderpath += file.FileName;
        string serverFolder = Path.Combine(_webHostEnvironment.WebRootPath, folderpath);
        await file.CopyToAsync(new FileStream(serverFolder, FileMode.Create));
        return "/" + folderpath;
    }

    public IActionResult Index()
    {
        var data = _context.FacultyModels.ToList();
        ViewBag.data = data;
        return View();
    }

    public IActionResult AddFaculty()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> AddFaculty(FacultyModel facultyModel, IFormFile file)
    {
        string folder = "file/";
        facultyModel.file = await UploadImage(folder, file);
        _context.FacultyModels.Add(facultyModel);
        _context.SaveChanges();
        return RedirectToAction("Index");
    }

    public async Task<IActionResult> UpdateFaculty(int id)
    {
        var facultyModel= await _context.FacultyModels.FindAsync(id);
        ViewBag.data = facultyModel;
        return View(facultyModel);
        TempData["ID"] = id;
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> UpdateFaculty( int id, FacultyModel facultyModel, IFormFile? file, string name, string description)
    {
        if (file == null)
        {
            var faculty = _context.FacultyModels.Where(f => f.s_no == id).FirstOrDefault();
            faculty.name = facultyModel.name;
            faculty.description = description;
            await _context.SaveChangesAsync();
        }
        else
        {
            string folder = "file/";
            facultyModel.file = await UploadImage(folder, file);
            _context.FacultyModels.Update(facultyModel);
            await _context.SaveChangesAsync();
        }

        return RedirectToAction("Index");
    }

    public IActionResult AppointHod()
    {
        return View();
    }

    public IActionResult UpdateHod()
    {
        return View();
    }

    public IActionResult DeleteFaculty(int id)
    {
         var data = _context.FacultyModels.Find(id);
         _context.FacultyModels.Remove(data);
         return RedirectToAction("Index");
    }
}

下面是我的视图,其中包含select教师列表

<form>
                         <div class="form-group">
                             <label for="input-1">Type</label>
                             <select class="form-control" id="input-1" placeholder="Enter type" name="type" required list="faculty">
                             <datalist id="faculty">
                                 <option > Bachelor </option>
                                 <option > Master</option>
                             </datalist>
                             </select>
                         </div>
                         
                         <div class="form-group">
                             <label for="input-2">Faculty</label>
                             <input type="text" class="form-control" id="input-2" placeholder="Enter semester/year" name="faculty" required list="teacher">
                             <datalist id="teacher">
                                 <option value="Boston"/>
                                 <option value="Cambridge"/>
                             </datalist>
                         </div>
                         
                         <div class="form-group">
                             <label for="input-3">Program Name</label>
                             <input type="text" class="form-control" id="input-3" placeholder="Enter Name" name="name" required>
                         </div>
                         <div class="form-group">
                             <label for="input-4">Description</label>
                             <input type="text" class="form-control" id="input-4" placeholder="Enter Description" name="description" required>
                         </div>
                         <div class="form-group">
                             <label for="input-5">File(syllabus)</label>
                             <input type="file" class="form-control" id="input-5" name="file">
                         </div>
                         <div class="form-group">
                             <div class="form-group">
                                 <label for="input-6">System</label>
                                 <select class="form-control" id="input-6" placeholder="Enter type" name="system" required list="system">
                                     <datalist id="system">
                                         <option > Yearly </option>
                                         <option > Semester</option>
                                     </datalist>
                                 </select>
                             </div>
                             <div class="form-group">
                                 <label for="input-7">Number of year/sem</label>
                                 <input type="number" class="form-control" id="input-7" placeholder="Enter number of year/sem" name="yearsem" required>
                             </div>
                             <button type="submit" class="btn btn-light px-5"> Add</button>
                         </div>
</form>

我只想用教员姓名填充 select 列表,并在程序模型中插入 selected 教员的 s_no 作为外键。

下面是一个工作demo,你可以参考一下。

程序模型

 public class ProgramModel
    {
        [Key]
        public int ProgramModels_no { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public string? file { get; set; }

        public string type { get; set; }
        public string system { get; set; }
        public string? director { get; set; }
        public int sem_year { get; set; }
       
        [ForeignKey("FacultyModels_no")]
        public virtual FacultyModel FacultyModel { get; set; }
        public int FacultyModels_no { get; set; }
    }

FacultyModel

public class FacultyModel
    {
        [Key]
        public int FacultyModels_no { get; set; }
        public string name { get; set; }
        public string description { get; set; }
        public string? file { get; set; }
        public string? hod { get; set; }
        public virtual ICollection<ProgramModel> ProgramModels { get; set; }
    }

在 ProgramModel 的控制器中,我在创建操作中添加了以下代码:

 ViewData["Faculty"] = new SelectList(_context.Set<FacultyModel>(), "FacultyModels_no", "name")

在创建视图中,我添加如下:

 <div class="form-group">
      <label asp-for="FacultyModels_no" class="control-label"></label>
      <select asp-for="FacultyModels_no" class ="form-control" asp-items="ViewBag.Faculty"></select>
 </div>

结果: