DEV Community

alcam1965
alcam1965

Posted on

Need help creating new child record with foreign key of paren

I'm building a CRUD Application to manage my company's back end and having issues with creating a new child record for a parent. The standard auto-generated controller based on the model is set up to create a new record but not a new child record so I need to modify the controller and or the models. The models involved are: Bundle.cs and Agreement.cs:

using System;
using System.Collections.Generic;

namespace AdminPortal.Models
{
    public partial class Bundle
    {
        public int Id { get; set; }
        public DateTime StartUtc { get; set; }
        public DateTime EndUtc { get; set; }
        public int Quantity { get; set; }
        public int? AgreementId { get; set; }
        public decimal? BundlePrice { get; set; }

        public virtual Agreement? Agreement { get; set; }
    }
}

Enter fullscreen mode Exit fullscreen mode
using System;
using System.Collections.Generic;

namespace AdminPortal.Models
{
    public partial class Agreement
    {
        public Agreement()
        {
            AgreementAmendments = new HashSet<AgreementAmendment>();
            Bundles = new HashSet<Bundle>();
            Invoices = new HashSet<Invoice>();
        }

        public int Id { get; set; }
        public int OrgId { get; set; }
        public string? AgreementNumber { get; set; }
        public string? IrespondReference { get; set; }
        public string? DocumentLink { get; set; }

        public virtual Organization Org { get; set; } = null!;
        public virtual ICollection<AgreementAmendment> AgreementAmendments { get; set; }
        public virtual ICollection<Bundle> Bundles { get; set; }
        public virtual ICollection<Invoice> Invoices { get; set; }
    }
}

Enter fullscreen mode Exit fullscreen mode

This is the create method in the Controller

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,StartUtc,EndUtc,Quantity,AgreementId,BundlePrice")] Bundle bundle)
        {
            if (ModelState.IsValid)
            {
                _context.Add(bundle);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(bundle);
        }
Enter fullscreen mode Exit fullscreen mode

I'm new to EF Core so don't even know where to start.

Top comments (0)