在 EF 6.1 中保存多对多关系

Saving many to many relationship in EF 6.1

我已经阅读了许多关于使用 EF 6.1 保存多对多关系的主题,但我没有进一步了解。 table 与 reservationIdfacilityId 的连接在我保存预订后仍然是空的。

这些是我的模型:

public class Reservation
{ 
    [Key]
    public int reservationId { get; set; }

    //Lijst met Facilities, Many to Many
    public virtual ICollection<Facility> FacilitiesList { get; set; }
}

public class Facility
{
    [Key]
    public int FacilityId { get; set; }
    public decimal FacilityPrice { get; set; }
    public string FacilityType { get; set; }

    //Many to Many
    public virtual ICollection<Reservation> reservationList { get; set; }

    public Facility()
    {
        //Instantiate our implementation of ICollection
        this.reservationList = new HashSet<Reservation>();
    }
}

我通过覆盖 OnModelCreating 创建连接 table:

public partial class DataContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<Reservation>()
                    .HasMany<Facility>(s => s.FacilitiesList)
                    .WithMany(c => c.reservationList)
                    .Map(cs =>
                    {
                        cs.MapLeftKey("ReservationId");
                        cs.MapRightKey("FacilityId");
                        cs.ToTable("ReservationFacility");
                    });

    }
}

编辑:这是我保存预订的地方:

public ActionResult Create()
    {
        ViewBag.FacilitiesList = new SelectList(_facilityrepository.GetAll(), "FacilityId", "FacilityType");
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ReservationId,ArrivalDate,LeaveDate,CampingSpotId,UserId,PersonsAmount,FacilityType,FacilityPrice")] Reservation reservation) 
    {
        _reservationrepository.Add(reservation);
        return RedirectToAction("ShowAvailableSpots", new { ArrivalDate = reservation.ArrivalDate, LeaveDate = reservation.LeaveDate, ReservationID = reservation.ReservationId });
    }

现在我有了 table。我可以保存设施,并且在使用 MultiSelectList 创建预订时可以 select 它们。

为什么连接 table 总是空的?我需要做什么来填充 FacilitiesList 以便我可以在我的项目中的任何地方获取这些数据?

因为我对此完全陌生,所以我不知道我需要初始化和填充列表。感谢@dellywheel 为我指明了正确的方向!

这是工作代码:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ReservationId,ArrivalDate,LeaveDate,CampingSpotId,UserId,PersonsAmount,FacilityType,FacilityPrice")] Reservation reservation, int[] SelectedFacilities) 
    {
        //Instantiate our facilities list!
        reservation.FacilitiesList = new List<Facility>();

        foreach (int facId in SelectedFacilities)
        {
            var facType = _facilityrepository.GetFacilityType(facId);
            var facPrice = _facilityrepository.GetFacilityPricePerDay(facId);
            reservation.FacilitiesList.Add(new Facility { FacilityId = facId, FacilityType = facType, FacilityPrice = facPrice} );
        }

        _reservationrepository.Add(reservation);
        return View() //code omitted 
    }