Home > Enterprise >  Having trouble to update new data to a table in MVC using Entity Framework
Having trouble to update new data to a table in MVC using Entity Framework

Time:09-17

I have a Cinema Model:

public class Cinema
    {
        public int Id { get; set; }

        [Required]
        [StringLength(255)]
        public string Name { get; set; }

        [Required]
        public string Address { get; set; }

        [Required]
        [Range(0, int.MaxValue, ErrorMessage = "Please enter valid number")]
        [Display(Name = "Total Seats")]
        public int TotalSeatsNumber { get; set; }

        public List<Seat>TotalSeats { get; set; }

        public OpeningHour OpeningHour { get; set; }

        [Required]
        [Display(Name = "Opens At")]
        public byte OpeningHourId { get; set; }

        public ClosingHour ClosingHour { get; set; }

        [Required]
        [Display(Name = "Closes At")]
        public byte ClosingHourId { get; set; }

        public Cinema() { }

I have a TotalSeatsNumber property, so when the admin fills a form (Inside the website) to create a new cinema, he has to specify how many seats the cinema should contain.

I've also created a List of Seats called TotalsSeats, which later I try to initialize with seats according to the number of seats the admin chose. You can see what I'm trying to do here:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Save(Cinema cinema)
        {
            if (!ModelState.IsValid)
            {
                var viewModel = new CinemaFormViewModel(cinema)
                {
                    OpeningHours = _context.OpeningHours.ToList(),
                    ClosingHours = _context.ClosingHours.ToList()
                };
                return View("CinemaForm", viewModel);
            }
            if (cinema.Id == 0)
            {
                cinema.TotalSeats = SetSeats(cinema.TotalSeatsNumber);
                _context.Cinemas.Add(cinema);
            }
            else
            {
                var cinemaInDb = _context.Cinemas.Single(c => c.Id == cinema.Id);

                cinemaInDb.Name = cinema.Name;
                cinemaInDb.Address = cinema.Address;
                cinemaInDb.TotalSeatsNumber = cinema.TotalSeatsNumber;
                cinemaInDb.TotalSeats = cinema.TotalSeats;
                cinemaInDb.OpeningHourId = cinema.OpeningHourId;
                cinemaInDb.ClosingHourId = cinema.ClosingHourId;
            }
            _context.SaveChanges();

            return RedirectToAction("Index", "Cinemas");
        }

The SetSeats function returns a list of Seats where I initialize their Id, location, and availability. Just in case, I will add my Seat Model and SetSeats function here:

public class Seat
    {
        public int Id { get; set; }

        [Required]
        public string Location { get; set; }

        [Required]
        public bool isAvailable { get; set; }

        public Seat()
        {
            isAvailable = true;
        }
    }
public List<Seat> SetSeats(int totalSeatsNumber)
        {
            List<Seat> totalSeats = new List<Seat>();
            char rowLetter = 'a';
            int seatNumInRow = 1;
            for (int i = 1; i <= totalSeatsNumber; i  , seatNumInRow  )
            {
                totalSeats.Add(new Seat() { Id = i, Location = rowLetter   (""   seatNumInRow), isAvailable = true });
                if ((i % 10) == 0)
                {
                    rowLetter  ;
                    seatNumInRow = 0;
                }
            }

            return totalSeats;
        }

The reason I'm trying to do this is that I want that the user will be able to choose a specific seat when he orders tickets for a movie in a certain cinema.

The problem is when I try to SaveChanges(), it throws me an exception:

System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.'

When debugging, I can see my "cinema" instance is updated properly, exactly like I wanted. But it fails when trying to save it to the DB.

CodePudding user response:

your Seat class doesnt have any relations with Cinema class, but you are trying to add a list , so add a foreign key CinemaId

public class Seat
 {
        public int Id { get; set; }

         ......

         public int CinemaId { get; set; }

         public virtual Cinema Cinema {get; set;}
}

you will have to migrate to db after changing

CodePudding user response:

You have to migrate first to make sure the database scheme go async with your DbModels in C#.

  • Related