C
C#3y ago
Luciferno

How to keep track of third property in Many-To-Many

I have 2 models one that is Reservation and one that is Menu, They have a many-to-many relation but I wanna keep track on the reservation how many times one menu is ordered for that resrevation. This is my current many-to-many table :
public int ReservationId { get; set; }
public Reservation Reservation { get; set; }

public int MenuId { get; set; }
public int TimesOrdered { get; set; } <-- this property needs to keep track of how many times a menu has been ordered.
public Menu Menu { get; set; }
public int ReservationId { get; set; }
public Reservation Reservation { get; set; }

public int MenuId { get; set; }
public int TimesOrdered { get; set; } <-- this property needs to keep track of how many times a menu has been ordered.
public Menu Menu { get; set; }
This is my current OnModelCreating for that table
modelBuilder.Entity<Reservation>()
.HasMany(x => x.Menus)
.WithMany(x => x.Reservations)
.UsingEntity<ReservationMenu>(
rm => rm.HasOne(x => x.Menu).WithMany().HasForeignKey(k => k.MenuId),
rm => rm.HasOne(x => x.Reservation).WithMany().HasForeignKey(k => k.ReservationId),
rm =>
{
rm.HasKey(p => new { p.MenuId, p.ReservationId });
}
);
modelBuilder.Entity<Reservation>()
.HasMany(x => x.Menus)
.WithMany(x => x.Reservations)
.UsingEntity<ReservationMenu>(
rm => rm.HasOne(x => x.Menu).WithMany().HasForeignKey(k => k.MenuId),
rm => rm.HasOne(x => x.Reservation).WithMany().HasForeignKey(k => k.ReservationId),
rm =>
{
rm.HasKey(p => new { p.MenuId, p.ReservationId });
}
);
I am kinda stuck on how to approach this.
2 Replies
undisputed world champions
why do you want to store this separately? cant you query it with something like _context.Menus.Count(m => m.Reservations.Any(r => r.Id == reservationId))?
Luciferno
LucifernoOP3y ago
I could try that good point That worked!
Want results from more Discord servers?
Add your server