繁体   English   中英

c# Razor 页面,EF Core,如何通过代码生成子记录并将其添加到尚未使用添加的父记录中

[英]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 using

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

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 创建页面 - 请注意,该页面只有在我创建时供父级填写的字段,我想在代码中生成所有子记录并将整个事务保存在一个 go 中。

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 object,如下所示:

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

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

结果:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM