FK ASP.NET CORE Razor CRUD 项目表中的值为空

问题描述 投票:0回答:0

我有一个问题,我一直试图解决一段时间,但我被卡住了。

我正在使用 EF Core 在 ASP.NET CORE RAZOR CRUD 中做一个 Book 项目。我有两个模型类 Category 和 libraryItem。

类别模型类。

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace LibraryManagement.Models
{
    public class Category
    {

        public int ID { get; set; }
        [Required]
        [StringLength(50)]
        public string? CategoryName { get; set; }
    }
}

LibraryItem 模型类

using Microsoft.AspNetCore.Mvc.Rendering;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace LibraryManagement.Models
{
    public class LibraryItem
    {

        public int ID { get; set; }
        public virtual Category? Category { get; set; }

        [RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$", ErrorMessage = "Only Text Please! No numbers!")]
        [Required]
        public string? Title { get; set; }
        [RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$", ErrorMessage = "Only text please!")]
        [Required]
        public string? Author { get; set; }
        [Required]
        [Range(1, 1000)]
        public Nullable<int> Pages { get; set; }

        [Range(1, 1000)]
        public Nullable<int> RunTimeMinutes { get; set; }

        public bool isBorrowable { get; set; }
        [RegularExpression(@"^[A-Z]+[a-zA-Z\s]*$", ErrorMessage = "Borrower cant be number! Only text!")]
        public string? Borrower { get; set; }
        [DataType(DataType.Date)]
        public Nullable<DateTime> BorrowerDate { get; set; }
        public string? Type { get; set; }
        public static IEnumerable<SelectListItem>? TypeOptions()
        {
            return new[]
            {
                new SelectListItem { Text = "book", Value = "book" },
                new SelectListItem { Text="reference book", Value="reference book"},
                new SelectListItem { Text="dvd", Value="dvd" },
                new SelectListItem{ Text="audio book", Value="audio book"}
            };
        }

    }
}

创建新的 LibraryItem 类

using LibraryManagement.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;

namespace LibraryManagement.Pages.ItemsToBorrow
{
    public class CreateModel : PageModel
    {
        private readonly Data.LibraryManagementContext _context;

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

        public IActionResult OnGet()
        {
            List<Category> categories = _context.Category.ToList();
            ViewData["Categories"] = new SelectList(categories, "ID", "CategoryName");
            //LibraryItems = await _context.LibraryItem.Include(x => x.Category).ToListAsync();
            return Page();
        }

        [BindProperty]
        public LibraryItem LibraryItem { get; set; } = default!;
        public Category LibraryCategory { get; set; }
        public SelectList getCategories { get; set; }

        public IList<LibraryItem> LibraryItems { get; set; } = default!;


        public SelectList getTypes { get; set; }

        // To protect from overposting attacks, see https://aka.ms/RazorPagesCRUD
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid || _context.LibraryItem == null || LibraryItem == null)
            {
                return Page();
            }
            _context.LibraryItem.Add(LibraryItem);
            await _context.SaveChangesAsync();

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

索引

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

namespace LibraryManagement.Pages.ItemsToBorrow
{
    public class IndexModel : PageModel
    {
        private readonly LibraryManagementContext _context;

        public IndexModel(LibraryManagement.Data.LibraryManagementContext context)
        {
            _context = context;
        }

        public IList<LibraryItem> LibraryItem { get;set; } = default!;


        [BindProperty(SupportsGet = true)]
        public string? SearchString { get; set; }

        public SelectList? Genres { get; set; }

        [BindProperty(SupportsGet = true)]
        public string? MovieGenre { get; set; }
        [BindProperty(SupportsGet = true)]
        public string? TypeItem { get; set; }

        public async Task OnGetAsync()
        {
            // Use LINQ to get list of genres.
            IQueryable<string> genreQuery = from m in _context.LibraryItem
                                            orderby m.Type
                                            select m.Type;

            //var movies = from m in _context.LibraryItem
            //             select m;
            var libraryTypes = from m in _context.LibraryItem
                               select m;



            if (!string.IsNullOrEmpty(TypeItem))
            {
                libraryTypes = libraryTypes.Where(x => x.Type == TypeItem);
            }
            Genres = new SelectList(await genreQuery.Distinct().ToListAsync());
            ////_context.LibraryItem.Include(e => e.Category).ToList();
            LibraryItem = await _context.LibraryItem.Include(c => c.Category).ToListAsync();
            //LibraryItem = await libraryTypes.ToListAsync();

        }
    }
}

当我尝试将新项目添加到 LibraryItem 中并将类别作为 FK 字段时,我根本没有收到任何错误消息,但它不会将类别插入到表行中。该列是空白的。

https://i.imgur.com/I8lHzCP.png

我在 Create.html 中用类别表中的值填充下拉列表,这样就可以了。将新类别添加到另一个表会使用新值更新下拉列表,所以没有问题。

但索引在类别列中显示为空白。几天来一直在尝试解决它,我知道 EF 核心,但它可能是某些导航的问题。

我曾尝试在 index.html.cs 中执行 LINQ 查询以尝试解决问题(如果问题出在表视图中但没有解决任何问题)。

我尝试更改为 Category.CategoryName,但那也没有用。

<select asp-for="LibraryItem.Category.CategoryName"

我被卡住了,一直在努力解决这个问题,但这只会让我更加困惑。

entity-framework asp.net-core razor foreign-keys one-to-many
© www.soinside.com 2019 - 2024. All rights reserved.