asp.net Create方法不存储

mspsb9vt  于 2022-12-27  发布在  .NET
关注(0)|答案(1)|浏览(118)
namespace Teatastic.Models
{
    public class Tea
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [StringLength(100)]
        [DataType(DataType.Text)]
        public string Name { get; set; }

        [Required]
        public double Price { get; set; }

        //Relationships
        public List<Function>? Functions { get; set; }

        [NotMapped]
        public List<int> FunctionIds { get; set; }

        public int BrandId { get; set; }
        public Brand Brand { get; set; }

    }
}
using Microsoft.Extensions.Hosting;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Drawing;

namespace Teatastic.Models
{
    public class Brand
    {
        public int Id { get; set; }

        [Required]
        [StringLength(100)]
        [DataType(DataType.Text)]
        public string Name { get; set; }

        [NotMapped]
        public Image? Logo { get; set; }

        public List<Tea>? Teas{ get; set; }

    }
}

最后,这是TeasController中的HttpPost方法

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Name,Price,FunctionIds,BrandId")] Tea tea)
        {

            if (ModelState.IsValid)
            {
                if (tea.Functions == null)
                {
                    tea.Functions = new List<Function>();
                }
                foreach (int FunctionId in tea.FunctionIds)
                {
                    tea.Functions.Add(_context.Function.FirstOrDefault(f => f.Id == FunctionId));
                }

                // Add brand to tea
                tea.Brand = _context.Brands.FirstOrDefault(b => b.Id == tea.BrandId);

                _context.Add(tea);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(tea);
        }

enter image description here
茶叶和品牌之间是一对多的关系(每种茶叶都有一个品牌,一个品牌可以有多个茶叶)。我试图将此对象存储到数据库中,但似乎品牌有问题。

66bbxpm5

66bbxpm51#

您可以使用.NET 6/.NET 7。在.NET 6中,不可为空的属性必须是必需的,否则ModelState将无效。
?添加到您的品牌属性:

public class Tea
{
    [Key]
    public int Id { get; set; }

    [Required]
    [StringLength(100)]
    [DataType(DataType.Text)]
    public string Name { get; set; }

    [Required]
    public double Price { get; set; }

    //Relationships
    public List<Function>? Functions { get; set; }

    [NotMapped]
    public List<int> FunctionIds { get; set; }

    public int BrandId { get; set; }
    public Brand? Brand { get; set; }

}

相关问题