phos456
phos456

Reputation: 19

EF Core - Add One to many records

Having Models Cinema and Hall with cardinality 1 <-> 0..n

Cinema.cs

public class Cinema
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int CinemaId { get; set; }

    [JsonPropertyName("name")]
    [Required]
    public string Name { get; set; }

    [JsonPropertyName("city")]
    [Required]
    public string City { get; set; }

    [JsonPropertyName("halls")]
    [Required]
    public List<Hall> Halls { get; set; } = new List<Hall();
}

Hall.cs

public class Hall
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int HallId { get; set; }
    public string Name { get; set; }
    public uint Capacity { get; set; }
    public Cinema Cinema { get; set; }
    public int Rows { get; set; }
    public List<Seat> Seats { get; set; } = new List<Seat>();
    public List<MovieShow> Shows { get; set; } = new List<MovieShow>();
}

CinemaRepository.cs

public async Task<Hall> AddHall(int cinemaId, Hall hall) {
  var cinema = await _context.Cinemas.FirstOrDefaultAsync(c => c.CinemaId == cinemaId);
  if (cinema == null) { return null; }
  var hallFound = cinema.Halls.FirstOrDefault(cinema => cinema.HallId == hall.HallId);
  if (hallFound != null) { return null; }
  hall.Cinema = cinema;
  await _context.Halls.AddAsync(hall);
  cinema.Halls.Add(hall);
  await _context.SaveChangesAsync();
  return hall;
}

But this only adds hall to the Halls, with its Cinema property being null.

Upvotes: 0

Views: 114

Answers (1)

Yinqiu
Yinqiu

Reputation: 7180

You should add foreign key to your Hall class and modify your Hall as follows:

    public class Hall
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int HallId { get; set; }
    public string Name { get; set; }
    public uint Capacity { get; set; }
    public int CinemaId { get;set;}
    public Cinema Cinema { get; set; }
    public int Rows { get; set; }
    public List<Seat> Seats { get; set; } = new List<Seat>();
    public List<MovieShow> Shows { get; set; } = new List<MovieShow>();
}

Then in your CinemaRepository:

 public async Task<Hall> AddHall(int cinemaId, Hall hall)
        {
            var cinema = _context.Cinemas.Include(c => c.Halls).FirstOrDefault(c => c.CinemaId == cinemaId);
            if (cinema == null) { return null; }
            var hallFound = cinema.Halls.FirstOrDefault(cinema => cinema.HallId == hall.HallId);
            if (hallFound != null) { return null; }
            cinema.Halls.Add(hall);
            await _context.SaveChangesAsync();
            return hall;
        }

Upvotes: 1

Related Questions