EF Core - 将一个添加到多个记录

EF Core - Add One to many records

具有基数为 1 <-> 0..n

的模型 CinemaHall

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;
}

但这只会将 hall 添加到 Halls,其 Cinema 属性 为空。

您应该将外键添加到您的 Hall class 并修改您的 Hall 如下:

    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>();
}

然后在你的 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;
        }