0

我正在尝试保存与该事件相对应的事件和事件详细信息。
它仅从循环中保存事件和第一个EventDetail

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

2 回答 2

1

移动

FutureEvents fe = new FutureEvents();

foreach循环内。您只创建了一个FutureEvents,因此保存了一个。

于 2013-07-29T03:41:49.897 回答
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);
}
于 2013-07-29T03:45:41.683 回答