我试图在我的项目中创建Order个对象.它一直返回到创建页面,但没有创建对象.因为对象本身与Pembersih对象有一对多关系(其中Pembersih有多个订单,而订单只有一个Pembersih).我正在使用Microsoft Visual Studio 2022和asp模板.net核心web MVC 6.0.我试图修改控制器,但没有成功,请帮助我.

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace CarWash1.Models
{
    public class Order
    {
        [Key]
        public int OrderId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string Phone { get; set; }

        public DateTime date { get; set; }
        [ForeignKey("PembersihId")]
        public int PembersihId { get; set; }
        public Pembersih pembersih { get; set; }
    }
}

清洁工反恐精英

namespace CarWash1.Models
{
    public class Pembersih
    {
        public Pembersih(){
            orders = new List<Order>();
        }
        public int PembersihId { get; set; }
        public string PembersihName { get; set; }
        public string PembersihPhone { get; set; }
        public List<Order> orders { get; set; }
    }
}

订单控制器.反恐精英

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using CarWash1.Data;
using CarWash1.Models;

namespace CarWash1.Controllers
{
    public class OrdersController : Controller
    {
        private readonly CarWash1Context _context;

        public OrdersController(CarWash1Context context)
        {
            _context = context;
        }

        // GET: Orders
        public async Task<IActionResult> Index()
        {
            var carWash1Context = _context.Order.Include(o => o.pembersih);
            return View(await carWash1Context.ToListAsync());
        }

        // GET: Orders/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null || _context.Order == null)
            {
                return NotFound();
            }

            var order = await _context.Order
                .Include(o => o.pembersih)
                .FirstOrDefaultAsync(m => m.OrderId == id);
            if (order == null)
            {
                return NotFound();
            }

            return View(order);
        }

        // GET: Orders/Create
        public IActionResult Create()
        {
            ViewData["PembersihId"] = new SelectList(_context.Set<Pembersih>(), "PembersihId", "PembersihId");
            return View();
        }

        // POST: Orders/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("OrderId,Name,Address,Phone,PembersihId")] Order order)
        {
            if (ModelState.IsValid)
            {
                _context.Add(order);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }

            ViewData["PembersihId"] = new SelectList(_context.Set<Pembersih>(), "PembersihId", "PembersihId", order.PembersihId);
            return View(order);
        }

        // GET: Orders/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null || _context.Order == null)
            {
                return NotFound();
            }

            var order = await _context.Order.FindAsync(id);
            if (order == null)
            {
                return NotFound();
            }
            ViewData["PembersihId"] = new SelectList(_context.Set<Pembersih>(), "PembersihId", "PembersihId", order.PembersihId);
            return View(order);
        }

        // POST: Orders/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("OrderId,Name,Address,Phone,PembersihId")] Order order)
        {
            if (id != order.OrderId)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(order);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!OrderExists(order.OrderId))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            ViewData["PembersihId"] = new SelectList(_context.Set<Pembersih>(), "PembersihId", "PembersihId", order.PembersihId);
            return View(order);
        }

        // GET: Orders/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null || _context.Order == null)
            {
                return NotFound();
            }

            var order = await _context.Order
                .Include(o => o.pembersih)
                .FirstOrDefaultAsync(m => m.OrderId == id);
            if (order == null)
            {
                return NotFound();
            }

            return View(order);
        }

        // POST: Orders/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            if (_context.Order == null)
            {
                return Problem("Entity set 'CarWash1Context.Order'  is null.");
            }
            var order = await _context.Order.FindAsync(id);
            if (order != null)
            {
                _context.Order.Remove(order);
            }
            
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool OrderExists(int id)
        {
          return (_context.Order?.Any(e => e.OrderId == id)).GetValueOrDefault();
        }
    }
}

清洁器控制器.反恐精英

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using CarWash1.Data;
using CarWash1.Models;

namespace CarWash1.Controllers
{
    public class PembersihsController : Controller
    {
        private readonly CarWash1Context _context;

        public PembersihsController(CarWash1Context context)
        {
            _context = context;
        }

        // GET: Pembersihs
        public async Task<IActionResult> Index()
        {
              return _context.Pembersih != null ? 
                          View(await _context.Pembersih.ToListAsync()) :
                          Problem("Entity set 'CarWash1Context.Pembersih'  is null.");
        }

        // GET: Pembersihs/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null || _context.Pembersih == null)
            {
                return NotFound();
            }

            var pembersih = await _context.Pembersih
                .FirstOrDefaultAsync(m => m.PembersihId == id);
            if (pembersih == null)
            {
                return NotFound();
            }

            return View(pembersih);
        }

        // GET: Pembersihs/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Pembersihs/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("PembersihId,PembersihName,PembersihPhone")] Pembersih pembersih)
        {
            if (ModelState.IsValid)
            {
                _context.Add(pembersih);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(pembersih);
        }

        // GET: Pembersihs/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null || _context.Pembersih == null)
            {
                return NotFound();
            }

            var pembersih = await _context.Pembersih.FindAsync(id);
            if (pembersih == null)
            {
                return NotFound();
            }
            return View(pembersih);
        }

        // POST: Pembersihs/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to.
        // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("PembersihId,PembersihName,PembersihPhone")] Pembersih pembersih)
        {
            if (id != pembersih.PembersihId)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(pembersih);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!PembersihExists(pembersih.PembersihId))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(pembersih);
        }

        // GET: Pembersihs/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null || _context.Pembersih == null)
            {
                return NotFound();
            }

            var pembersih = await _context.Pembersih
                .FirstOrDefaultAsync(m => m.PembersihId == id);
            if (pembersih == null)
            {
                return NotFound();
            }

            return View(pembersih);
        }

        // POST: Pembersihs/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            if (_context.Pembersih == null)
            {
                return Problem("Entity set 'CarWash1Context.Pembersih'  is null.");
            }
            var pembersih = await _context.Pembersih.FindAsync(id);
            if (pembersih != null)
            {
                _context.Pembersih.Remove(pembersih);
            }
            
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool PembersihExists(int id)
        {
          return (_context.Pembersih?.Any(e => e.PembersihId == id)).GetValueOrDefault();
        }
    }
}

创造cshtml

@model CarWash1.Models.Order

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Order</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Address" class="control-label"></label>
                <input asp-for="Address" class="form-control" />
                <span asp-validation-for="Address" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Phone" class="control-label"></label>
                <input asp-for="Phone" class="form-control" />
                <span asp-validation-for="Phone" class="text-danger"></span>
            </div>
             <div class="form-group">
                <label asp-for="date" class="control-label"></label>
                <input asp-for="date" class="form-control" />
                <span asp-validation-for="date" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="PembersihId" class="control-label"></label>
                <select asp-for="PembersihId" class ="form-control" asp-items="ViewBag.PembersihId"></select>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

推荐答案

由于您使用的是net 6.0,因此有2种 Select

  1. 例如,将所有类中未标记为必需的所有属性标记为可为Null
        public string? Name { get; set; }
        public string? Address { get; set; }
        public string? Phone { get; set; }
        ... and so on
  1. 或通过注释、删除或分解更改项目属性Nullable
<PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <!--<Nullable>enable</Nullable>-->
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

Csharp相关问答推荐

为什么使用DXGI输出复制和Direct 3D时捕获的图像数据全为零?

在WPF.NET 6中使用C++/WinRT组件(但实际上是任何WinRT组件)

当我使用NET6作为目标框架时,为什么DotNet使用NET8作为MS包?

. NET 8控制台应用程序DI错误无法解析Microsoft. Extension. Logging. ILoggerFactory类型的服务'''

此反射有什么问题.是否发送值转换委托?

自动映射程序在GroupBy之后使用项目

最新的Mediatr和具有同步方法的处理程序Handle:并非所有代码路径都返回值"

C#无法让WinForm进度条生成动画错误跨线程操作无效

为什么无法将对象转换为泛型类型

C#带主体的主构造函数?

如何在C#中将方法/线程启动传递给基本构造函数

使用Entity Framework6在对象中填充列表会导致列表大多为空

如何使用.NET6WPF打印车票?

.NET 6:如何防止系统生成的日志(log)?

在使用StringBuilder时,如何根据 colored颜色 设置为richTextBox中的特定行着色?

如何在.NET Maui中将事件与MVVM一起使用?

基于C#方法的EF核心过滤查询(缓冲与流)

HttpClient,上传文件时实现进度

除非首先访问使用的终结点,否则本地API上的终结点不起作用

XmlSerializer在遇到XML属性(命名空间)时崩溃