【问题标题】:c# Razor Pages, EF Core, How do I generate and add Child Records through Code to a Parent Record that has yet to be added usingc# Razor Pages,EF Core,如何通过代码生成子记录并将其添加到尚未使用的父记录中
【发布时间】:2021-03-28 15:50:03
【问题描述】:

我正在使用带有 EF Core 5 的 c# Razor Pages。我根本没有使用 MVC。我正在尝试为父记录(开始日期/结束日期的年份)自动生成子记录(一年中的月份)。我的模型中设置了关系:

namespace Seasons.Models
{
    public class AccountYears //Parent Record
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public Guid AccountYearsID { get; set; } 
            

        [Display(Name = "Accounts Year Name"), Required]
        public string AccountYearsName { get; set; }

        [Display(Name = "Start Date"), Required, DataType(DataType.Date)]
        public DateTime DateStart { get; set; }

        [Display(Name = "End Date"), Required, DataType(DataType.Date)]
        public DateTime DateEnd { get; set; }

        //AccountYearsMonths
        public List<AccountYearsMonths> AccountYearsMonths { get; set; }
    }
}

namespace Seasons.Models // Child Records
{
    public class AccountYearsMonths
    {

        // [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public Guid AccountYearsMonthsID { get; set; }

        [Required]
        public Guid AccountYearsID { get; set; }

        [Display(Name = "Month Name"), Required]
        public string AccountYearsMonthsName { get; set; }

        [Display(Name = "Start Date"), Required, DataType(DataType.Date)]
        public DateTime DateStart { get; set; }

        [Display(Name = "End Date"), Required, DataType(DataType.Date)]
        public DateTime DateEnd { get; set; }

        //AccountsYears
        public AccountYears AccountYears { get; set; }

    }

然后是我的 AccountYears 创建页面 - 请注意,该页面只有在我创建时供父级填写的字段,我想在代码中生成所有子记录并一次性保存整个事务。

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 MyApplication.Data;
using Seasons.Models;

namespace Seasons.Areas.Setup.Pages.FinanceAccountYears
{
    public class CreateModel : PageModel
    {
        private readonly MyApplication.Data.ApplicationDbContext _context;

        public CreateModel(MyApplication.Data.ApplicationDbContext context)
        {
            _context = context;
//            _context.Attach(AccountYearsMonths);
        }

        public IActionResult OnGet()
        {
            return Page();
        }

        [BindProperty]
        public AccountYears AccountYears { get; set; }
        public List<AccountYearsMonths> AccountYearsMonths { get; set; }

        // public List<AccountYearsMonths> AccountYearsMonths { get; set; }


        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            

            //AccYearsMonths();

            //var emptyAccountYears = new AccountYears();
            //if (await TryUpdateModelAsync<AccountYears>(
            //        emptyAccountYears,
            //        "AccYears",
            //        ay => ay.AccountYearsID, ay => ay.AccountYearsName, ay => ay.DateStart, ay => ay.DateEnd, ay => ay.Status))
            //{
            //    _context.AccountYears.Add(emptyAccountYears);

            AccYearsMonths();

            _context.AccountYears.Add(AccountYears);
            await _context.SaveChangesAsync();

            //Guid AddedID = AccountYears.AccountYearsID;

            //AccYearsMonths(AddedID);

            //_context.AccountYears.Update(AccountYears);
            //await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }


        public void AccYearsMonths()
        {

            // AccountYearsMonths = new List<AccountYearsMonths>();

            DateTime MasterStartDate = AccountYears.DateStart;
            DateTime MasterEndDate = AccountYears.DateEnd;
            
            // Get the StartDate, MonthEndDate, and YearEndDate into variables

            DateTime Date1 = new DateTime(MasterStartDate.Year, MasterStartDate.Month, 01);
            DateTime Date2 = new DateTime(Date1.Year, Date1.Month, DateTime.DaysInMonth(Date1.Year, Date1.Month));
            string MonthName = new string(Date1.ToString("MMM"));
            

            while (Date1 < MasterEndDate)
                {

                AccountYears.AccountYearsMonths.Add(new AccountYearsMonths
                {
                    AccountYearsMonthsName = MonthName,
                    DateStart = Date1,
                    DateEnd = Date2,
                    Status = "OPEN"
                });

                //AccountYearsMonths d = new AccountYearsMonths
                //{
                //    AccountYearsMonthsName = MonthName,
                //    DateStart = Date1,
                //    DateEnd = Date2,
                //    Status = "OPEN",
                //    AccountYearsID = YearID

                //};

                // _context.AccountYearsMonths.Add(d);
                // AccountYearsMonths.Add(d);


                if (Date1.Month > 11)
                {
                    Date1 = new DateTime(Date1.Year + 1, 01, 01);
                }
                else
                {
                    Date1 = new DateTime(Date1.Year, Date1.Month + 1, 01);
                } // Endif
              
                Date2 = new DateTime(Date1.Year, Date1.Month, DateTime.DaysInMonth(Date1.Year, Date1.Month));
                MonthName = Date1.ToString("MMM");

            } // End While

           

        } //End AccYearMonths


    }
}

运行此代码时出现以下错误:System.NullReferenceException: 'Object reference not set to an instance of an object。'运行此行时会发生这种情况: AccountYears.AccountYearsMonths.Add(new AccountYearsMonths

从所有注释掉的代码中可以看出,我尝试了几种不同的方法。

任何帮助将不胜感激。

【问题讨论】:

  • 不知何故,我无法让模型识别 AccountYearsMonths 是 AccountsYears 表的子项。即使我尝试使用父级的 GUID 创建子级,模型仍然无法识别子记录。 - 我在这里能找到的唯一信息都与 MVC 有关,在这种情况下我只使用 Razor。

标签: c# asp.net-core razor entity-framework-core razor-pages


【解决方案1】:

您需要初始化AccountYearsMonths 对象,如下所示:

while (Date1 < MasterEndDate)
{
     //change here...
    AccountYears.AccountYearsMonths = new List<AccountYearsMonths>();

    AccountYears.AccountYearsMonths.Add(new AccountYearsMonths
    {
        AccountYearsMonthsName = MonthName,
        DateStart = Date1,
        DateEnd = Date2,
        Status = "OPEN"
    });
    //....
}

结果:

【讨论】:

  • 谢谢谢谢谢谢!!!诀窍是我在这里错过了 //change ... AccountYears.AccountYearsMonths = new List();。但是我把它移到了循环之外。当声明在循环内时,它只创建了一个月。将声明放在循环之前,然后我就可以构建月份列表了!!!因此,我并没有通过仅声明没有 AccountYears 的 AccountYearsMonths 来将父母与孩子结婚。字首。非常非常感谢@Rena !!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多