Search code examples
asp.net-core-mvcforeign-keysvisual-studio-2022modelstateasp.net-mvc-scaffolding

Visual Studio scaffolded Create form does not work in ASP.NET Core 8 MVC


I'm fairly new to .NET Core and I'm working on a mini project, an apartment booking website.

I've already made my data models and data tables for the site. When I scaffold a new controller with Razor views, the create form just doesn't work when there is a foreign key in the table.

The basic create for simple tables works. I tried everything, I gave ChatGPT all of my code and it still does not work. What am I doing wrong?

There are 2 data tables Apartments and Bookings. Here are the 2 data classes which are needed in the form (they inherit their ID from BaseEntity):

using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;

namespace Vendeghazak.Data
{
    public class Booking : BaseEntity
    {
        public int GuestID { get; set; }
        public DateTime CheckInDate { get; set; }
        public DateTime CheckOutDate { get; set; }
        public string? Comment { get; set; }
        public string? Status { get; set; }
        public bool Cancelled { get; set; }
        
        [ForeignKey("ApartmentId")]
        public int ApartmentId { get; set; }
        public Apartment Apartment { get; set; }
        
        public int NumberOfPersons { get; set; }
        public int PersonsUnder18 { get; set; }
        public string BillingAddress { get; set; }
        public string BillingEmail { get; set;}
    }

    public class Apartment : BaseEntity
    {
        public string Name { get; set; }
        public int Capacity { get; set; }
    }

    public partial class BaseEntity
    {
        public int Id { get; set; }
        public DateTime DateCreated { get; set; }
        public DateTime DateModified { get; set; }
    }
}

I tried removing the Id from the foreign key annotation, but it didn't help. When I submit the form, the Apartments subkey always be null and the ModelState is invalid because of that. There is a dropdown list for the apartments and I tried different methods to populate it correctly, without success.

I also tried hard coding the ID value of the apartment into the view then manually assign it in the controller, but the Apartments subkey is always null after submission.

What am I doing wrong?


Solution

  • By default LINQ is not loading the Apartments table when you retrieve Bookings.

    Add the following to the LINQ statement that loads Booking.

    context.Booking
    .Include(x => x.Apartment)
    .FirstOrDefaultAsync();