繁体   English   中英

EF Core,一对多关系 - 如何使用单个视图在两个表中插入记录?

[英]EF Core, one-to-many relationship - how to insert records in both tables with a single view?

我有两个模型设置如下:

public class NewCourseCategoryForm
{
    public int NewCourseCategoryFormID { get; set; }            
    
    public virtual ICollection<ProposedCourse> ProposedCourse { get; set; }
}

进而:

public class ProposedCourse
{
    public int ProposedCourseID { get; set; }           
    public string ProposedCourseName { get; set; }
    public string ProposedCourseDescription { get; set; }
    
    public NewCourseCategoryForm  { get; set; }
}

在我的 DbContext 类定义中,我有以下代码定义了上述两个表之间的关系:

modelBuilder.Entity<NewCourseCategoryForm>(entity =>
{
    entity.HasKey(e => NewCourseCategoryFormID                  
    entity.Property(e => e.NewCourseCategoryFormID).HasColumnName("NewCourseCategoryFormID");

    entity.HasMany(d => d.ProposedCourse)
          .WithOne(p => p.NewCourseCategoryForm);

    modelBuilder.Entity<ProposedCourse>(entity =>
    {
        entity.HasKey(e => e.ProposedCourseID);    
        entity.Property(e => e.ProposedCourseName).HasColumnName("ProposedCourseName");
        entity.Property(e => e.ProposedCourseDescription).HasColumnName("ProposedCourseDescription");                   
    });

我想为NewCourseCategoryForm页面创建 CRUD 页面。 在“创建”页面,而不是看到ProposedCourseID ,我想看看相关的文本框ProposedCourse模型ProposedCourseNameProposedCourseDescription 每当用户创建新的NewCourseCategoryForm ,我都希望将记录输入到两个表中,如下所示:

+----------------------------+------------------+
| NewCourseCategoryFormID    | ProposedCourseID |
+----------------------------+------------------+
| 1                          | 123              |
+----------------------------+------------------+

+------------------+--------------------+---------------------------+
| ProposedCourseID | ProposedCourseName | ProposedCourseDescription |
+------------------+--------------------+---------------------------+
| 123              | Algebra 101        | Beginner algebra          |
+------------------+--------------------+---------------------------+

我确信 Entity Framework 可以处理这样的事情,但我不知道从哪里开始寻找。 我怎样才能做到这一点? 我什至需要用户能够输入动态数量的“建议课程”。 那么我怎样才能做到这一点呢?

这应该可以解决问题:

CourseViewModels.cs:

using System.Collections.Generic;

namespace Test.Models
{
    public class NewCourseCategoryForm
    {
        public int NewCourseCategoryFormID { get; set; }            
        
        public virtual ICollection<ProposedCourse> ProposedCourses { get; set; }
    }

    public class ProposedCourse
    {
        public int ProposedCourseID { get; set; }           
        public string ProposedCourseName { get; set; }
        public string ProposedCourseDescription { get; set; }
        
        public NewCourseCategoryForm Form { get; set; }
    }
}

CoursesController.cs:

using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Test.Models;

namespace Test.Controllers
{
    public class CoursesController : Controller
    {
        private readonly ILogger<CoursesController> _logger;

        public CoursesController(ILogger<CoursesController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Create(NewCourseCategoryForm form)
        {
            var newForm = new NewCourseCategoryForm
            {
                ProposedCourses = form.ProposedCourses.Select(s => new ProposedCourse
                {
                    ProposedCourseName = s.ProposedCourseName,
                    ProposedCourseDescription = s.ProposedCourseDescription
                }).ToList()
            };

            // _context.NewCourseCategoryForms.Add(newForm);
            // _context.SaveChanges();

            return RedirectToAction("Create");
        }
    }
}

创建.cshtml:

@model NewCourseCategoryForm
@{
    ViewData["Title"] = "Home Page";
}

<form method="post">
    <div id="courses" class="row">
        <div class="col-md-6">
            <div class="form-group">
                <label>Course name</label>
                <input type="text" class="form-control" name="ProposedCourses[0].ProposedCourseName" placeholder="Name...">
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <label>Course description</label>
                <input type="text" class="form-control" name="ProposedCourses[0].ProposedCourseDescription" placeholder="Description...">
            </div>
        </div>
    </div>

    <button class="btn btn-primary" type="button" onclick="create()">New...</button>
    <button class="btn btn-secondary" type="submit">Create</button>
</form>

@section Scripts
{
    <script type="text/javascript">
        var counter = 1;

        const create = () => {
            $("#courses").append(`
                <div class="col-md-6">
                    <div class="form-group">
                        <label>Course name</label>
                        <input type="text" class="form-control" name="ProposedCourses[` + counter + `].ProposedCourseName" placeholder="Name...">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label>Course description</label>
                        <input type="text" class="form-control" name="ProposedCourses[` + counter + `].ProposedCourseDescription" placeholder="Description...">
                    </div>
                </div>
            `);

            counter++;
        }
    </script>
}

课程页面

发布的数据集

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM