Recommand · October 14, 2021 0

Create parent with many children simultaneously in C# ASP.NET and Razor

I’m trying to create a form for someone to create a poll with a question and option list. In my razor code, I can see that the question and options are saving to the properties, but only the question is saving in the database. I’m thinking it has to do with how I’m saving the context. I have seen several other tutorials showing how to do this by assigning variables, but I don’t believe that will work for me since I need the question Id to save with the Option Id.

Models

    public class Question
{
    [Required]
    public int ID { get; set; }

    [StringLength(25, MinimumLength = 3)]
    public string UName { get; set; }

    [Required]
    [StringLength(170, MinimumLength = 3)]
    public string Poll { get; set; }

    public List<Option> Option { get; set; }
}

public class Option
{
    [Required]
    public int ID { get; set; }

    [Required]
    public int QuestionID { get; set; }

    [Required]
    [StringLength(20)]
    public string OptionName { get; set; }

    public Question Question { get; set; }

    public ICollection<Answer> Answer { get; set; }
}

Create PageModel

    public class CreateModel : PageModel
{
    private readonly Pollster_v5.Data.ApplicationDbContext _context;

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

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

    [BindProperty]
    public Question Question { get; set; }

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

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            var message = string.Join(" | ", ModelState.Values
                .SelectMany(v => v.Errors)
                .Select(e => e.ErrorMessage));
            return Page();
        }

        Question.Option = new List<Option>();

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

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