在EF 6.1中保存多对多的关系

时间:2015-04-03 13:45:10

标签: c# entity-framework many-to-many

我已经阅读了许多关于与EF 6.1保存多对多关系的主题,但我还没有进一步了解。我保存预订后,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来创建连接表:

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

现在我有了桌子。我可以保存设施,我可以在使用MultiSelectList创建预订时选择它们。

为什么连接表总是空的?我需要做些什么来填充FacilitiesList以便我可以在项目的任何位置获取此数据?

1 个答案:

答案 0 :(得分:0)

因为我对此完全陌生,所以我没有提到我需要初始化和填充列表的线索。感谢@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 
    }