我的问题是:我有两个桌子的房间和预订。它们与RoomReservation表中的许多对象有关。
public class Room
{
public int Id { get; set; }
public double CostNight { get; set; }
public virtual ICollection<Reservation> Reservation { get; set; }
}
public class Reservation
{
public int Id { get; set; }
public string DateOfEntry { get; set; }
public int NumberOfNights { get; set; }
public virtual ICollection<Room> Room { get; set; }
}
在我的DbContext上我配置了这个:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Reservation>().HasMany(c => c.Room)
.WithMany(s => s.Reservation)
.Map(t => t.MapLeftKey("RoomId")
.MapRightKey("ReservationId")
.ToTable("RoomReservation"));
}
按下按钮后,我将数据保存到数据库中:
public ActionResult Reservation(int number, string date, int roomid)
{
var reserv = new Reservation
{
NumberOfNights = number,
DateOfEntry = date
};
db.Reservation.Add(reserv);
db.SaveChanges();
}
如何将数据保存到RoomReservation表中?
答案 0 :(得分:0)
您需要从数据库中检索Room
的实例:
List<Room> selectedRooms = db.Rooms.Where(r => r.RoomId == roomid).ToList();
var reserv = new Reservation
{
NumberOfNights = number,
DateOfEntry = date,
Room = selectedRooms
};
db.Reservation.Add(reserv);
db.SaveChanges();