2013-07-29 89 views
0

我試圖保存與該事件相對應的Event和EventDetails。
它僅從循環中保存事件和第一個EventDetailEF只保存第一個子實體

public class Event 
{ 
    [Key] 
    public int CourseId { get; set; } 
    .. 
    public virtual ICollection<EventDetail> EventDetails{ get; set; } 
} 

控制器:

[HttpPost] 
public ActionResult Create(Event ev) 
{ 
     if (ModelState.IsValid) 
     { 

      IQueryable<EventDetail> eventList = ..; 

      FutureEvents fe = new FutureEvents(); 
      ICollection<FutureEvents> feCol = new Collection<FutureEvents>(); 

      foreach (EventDetail det in eventList) 
      { 
       fe.Name = ..; 
       db.Entry(fe).State = EntityState.Added; 
       feCol.Add(fe); 
      } 

      ev.EventDetails = feCol; 
      db.Event.Add(ev); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(ev); 
} 

回答

1

移動

FutureEvents fe = new FutureEvents(); 

foreach環內。你創建了一個FutureEvents,所以一個被保存。

+0

以及我不能相信我做到了! – user1770609

1

您創建了一個對象,然後在每次迭代中修改它。試試這個:

[HttpPost] 
public ActionResult Create(Event ev) 
{ 
     if (ModelState.IsValid) 
     { 

      IQueryable<EventDetail> eventList = ..; 

      ICollection<FutureEvents> feCol = new Collection<FutureEvents>(); 

      foreach (EventDetail det in eventList) 
      { 
       FutureEvents fe = new FutureEvents(); 
       fe.Name = ..; 
       db.Entry(fe).State = EntityState.Added; 
       feCol.Add(fe); 
      } 

      ev.EventDetails = feCol; 
      db.Event.Add(ev); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(ev); 
}