You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core MVC中无法创建Loan记录的技术求助

无法在Entity Framework Core中创建Loan记录的问题

使用Entity Framework Core开发ASP.NET Core MVC应用时,提交表单后数据库中未生成新的Loan记录,且未抛出任何异常。以下是项目配置与相关代码:

问题概述

模型Loan包含属性:

Id, BookId, MemberId, LoanDate, ReturnDate

LibraryContext已配置DbSet<Loan> Loans,Loan与Book、Member的关联关系已在OnModelCreating方法中设置。LoanController包含处理GET和POST请求的Create方法,POST方法负责处理表单提交以添加新Loan记录,Create视图包含对应字段的表单。

相关代码

Models/Loan.cs

using System;
using System.ComponentModel.DataAnnotations;

namespace LibraryManagementSystem.Models
{
    public class Loan
    {
        public int Id { get; set; }

        [Required]
        public int BookId { get; set; }

        public Book Book { get; set; }

        [Required]
        public int MemberId { get; set; }

        public Member Member { get; set; }

        [Required]
        public DateTime LoanDate { get; set; }

        public DateTime? ReturnDate { get; set; }
    }
}

LoanController.cs

public class LoanController : Controller
{
    private readonly LibraryContext _context;

    public LoanController(LibraryContext context)
    {
        _context = context;
    }

    // GET: Loan
    public async Task<IActionResult> Index()
    {
        var loans = await _context.Loans
            .Include(l => l.Book)
            .Include(l => l.Member)
            .ToListAsync();
        return View(loans);
    }

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

        var loan = await _context.Loans
            .Include(l => l.Book)
            .Include(l => l.Member)
            .FirstOrDefaultAsync(m => m.Id == id);
        if (loan == null)
        {
            return NotFound();
        }

        return View(loan);
    }

    // GET: Loan/Create
    public IActionResult Create()
    {
        ViewData["BookId"] = new SelectList(_context.Books, "Id", "Title");
        ViewData["MemberId"] = new SelectList(_context.Members, "Id", "Name");
        return View();
    }

    // POST: Loan/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,BookId,MemberId,LoanDate,ReturnDate")] Loan loan)
    {
        if (ModelState.IsValid)
        {
            _context.Add(loan);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        ViewData["BookId"] = new SelectList(_context.Books, "Id", "Title", loan.BookId);
        ViewData["MemberId"] = new SelectList(_context.Members, "Id", "Name", loan.MemberId);
        return View(loan);
    }

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

        var loan = await _context.Loans.FindAsync(id);
        if (loan == null)
        {
            return NotFound();
        }
        ViewData["BookId"] = new SelectList(_context.Books, "Id", "Title", loan.BookId);
        ViewData["MemberId"] = new SelectList(_context.Members, "Id", "Name", loan.MemberId);
        return View(loan);
    }

    // POST: Loan/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Id,BookId,MemberId,LoanDate,ReturnDate")] Loan loan)
    {
        if (id != loan.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(loan);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!LoanExists(loan.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        ViewData["BookId"] = new SelectList(_context.Books, "Id", "Title", loan.BookId);
        ViewData["MemberId"] = new SelectList(_context.Members, "Id", "Name", loan.MemberId);
        return View(loan);
    }

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

        var loan = await _context.Loans
            .Include(l => l.Book)
            .Include(l => l.Member)
            .FirstOrDefaultAsync(m => m.Id == id);
        if (loan == null)
        {
            return NotFound();
        }

        return View(loan);
    }

    // POST: Loan/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var loan = await _context.Loans.FindAsync(id);
        _context.Loans.Remove(loan);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool LoanExists(int id)
    {
        return _context.Loans.Any(e => e.Id == id);
    }
}

LoanCreate.cshtml

@page
@model LibManagementSystem.Pages.Loans.CreateModel

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

<h1>Create</h1>

<h4>Loan</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Loan.BookId" class="control-label"></label>
                <select asp-for="Loan.BookId" class ="form-control" asp-items="ViewBag.BookId"></select>
            </div>
            <div class="form-group">
                <label asp-for="Loan.MemberId" class="control-label"></label>
                <select asp-for="Loan.MemberId" class ="form-control" asp-items="ViewBag.MemberId"></select>
            </div>
            <div class="form-group">
                <label asp-for="Loan.LoanDate" class="control-label"></label>
                <input asp-for="Loan.LoanDate" class="form-control" />
                <span asp-validation-for="Loan.LoanDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Loan.ReturnDate" class="control-label"></label>
                <input asp-for="Loan.ReturnDate" class="form-control" />
                <span asp-validation-for="Loan.ReturnDate" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

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

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

LoanCreate.cshtml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using LibraryManagementSystem.Data;
using LibraryManagementSystem.Models;

namespace LibManagementSystem.Pages.Loans
{
    public class CreateModel : PageModel
    {
        private readonly LibraryManagementSystem.Data.LibraryContext _context;

        public CreateModel(LibraryManagementSystem.Data.LibraryContext context)
        {
            _context = context;
        }

        public IActionResult OnGet()
        {
            ViewData["BookId"] = new SelectList(_context.Books, "Id", "Id");
            ViewData["MemberId"] = new SelectList(_context.Members, "Id", "Id");
            return Page();
        }

        [BindProperty]
        public Loan Loan { get; set; } = default!;

        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            _context.Loans.Add(Loan);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }
    }
}

内容的提问来源于stack exchange,提问作者Haider sana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 02:24:50