编辑-根据要求,这是视图...
--开始编辑
@model salesWebTest.viewModel.vwbooking
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.bookings.bookingid)
@Html.EditorFor(model => model.bookings.name)
@foreach (var item in Model.traces)
{
@Html.EditorFor(m => item.contact_Name)
}
}
--结束编辑
--start original question 我有一个包含两个类的视图模型......
public class vwbooking
{
public booking bookings { get; set; }
public IEnumerable<trace> traces { get; set; }
}
预订和跟踪是 edmx 中的实体。
我想通过一次保存来更新这两个类中的数据。
这是我尝试过的...
public ActionResult Edit(vwbooking vwbooking)
{
if (ModelState.IsValid)
{
db.bookings.Attach(vwbooking.bookings);
db.Entry(vwbooking.bookings).State = EntityState.Modified;
vwbooking.traces.ToList().ForEach( //THE ERROR OCCURS HERE
t =>
{
db.traces.Attach(t);
db.Entry(t).State = EntityState.Modified;
});
db.SaveChanges();
}
}
如果我删除跟踪部分,预订部分将正确更新。
这是GET方法...
public ActionResult Edit(int id = 0)
{
booking booking = db.bookings.Find(id);
var viewModel = new vwbooking();
viewModel.bookings = booking;
viewModel.traces = (from l in db.traces where l.bookingid == booking.bookingid select l);
return View(viewModel);
}
这是我的数据库上下文类
public class salesContext : DbContext
{
public salesContext() : base()
{
Configuration.LazyLoadingEnabled = true;
}
public salesContext(string Connection) : base(Connection)
{
Configuration.LazyLoadingEnabled = true;
}
public DbSet<booking> bookings { get; set; }
public DbSet<trace> traces { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<booking>().HasKey(e => e.bookingid);
modelBuilder.Entity<trace>().HasKey(e => e.traceid);
}
}