Updating a collection of classes or viewmodel

妖精的绣舞 提交于 2019-12-13 08:53:38

问题


I have a viewModel that contains two classes...

public class vwbooking
{
    public booking bookings { get; set; }
    public IEnumerable<trace> traces { get; set; }
}

Booking and trace are entities in an edmx.

I want to update the data in these two class with one call to save.

This is what I've tried, along with several other unsuccessful "shot-in-the-dark" variants...

public ActionResult Edit(vwbooking vwbooking)
{
if (ModelState.IsValid)
{
    DbEntityEntry<vwbooking> entry = db.Entry(vwbooking);
    entry.Property(e => e.bookings.firstname).IsModified = true;

    db.SaveChanges();
}
}

I get the following error when calling the save method...

The entity type vwbooking is not part of the model for the current context.

The GET method loads successfully. The post is where I'm having trouble. This is the GET method...

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

This is my db context class

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

回答1:


The code for update your model is:

db.Attach(vwbooking.bookings)
db.ObjectStateManager.ChangeObjectState(vwbooking.bookings, System.Data.EntityState.Modified)

vwbooking.traces.ToList().ForEach(
  t =>
  {
  db.Attach(t);
  db.ObjectStateManager.ChangeObjectState(t, System.Data.EntityState.Modified);
  }
);

db.SaveChanges();

try this code in the Edit Controller



来源:https://stackoverflow.com/questions/19427402/updating-a-collection-of-classes-or-viewmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!