0

I am developing an ASP.Net MVC 3 Web application using Entity Framework 4.1, however, I am having an issue with updating the navigation entity of an entity.

I have an Entity called Shift

public partial class Shift
{
    public Shift()
    {
        this.Locations = new HashSet<ShiftLocation>();
    }

    public int shiftID { get; set; }
    public string shiftTitle { get; set; }

    public virtual ICollection<ShiftLocation> Locations { get; set; }

}

In my Shift Controller, I have two HttpPost methods to create and edit a Shift.

[HttpPost]
    public ActionResult CreateShift(ViewModelShift model)
    {

            if (ModelState.IsValid)
            {
                Shift shift = new Shift();
                shift = Mapper.Map<ViewModelShift, Shift>(model);

                //Create new shift location and add it to the newly created Shift
                ShiftLocation location = new ShiftLocation();
                location.locationID = model.locationID;
                shift.Locations.Add(location);

                _shiftService.AddShift(shift);

                return RedirectToAction("Index");
            }
}

[HttpPost]
    public ActionResult EditShift(ViewModelShift model)
    {

            if (ModelState.IsValid)
            {
                Shift shift = new Shift();
                shift = Mapper.Map<ViewModelShift, Shift>(model);


                ShiftLocation location = new ShiftLocation();
                //location = Mapper.Map<ViewModelShift, ShiftLocation>(model);
                location.shiftID = model.shiftID;
                location.locationID = model.locationID;
                shift.Locations.Add(location);

                _shiftService.UpdateShift(shift);

                return RedirectToAction("Index");
            }
        }

The CreateShift method works fine, ie, inserts a record into the database for a new Shift and also a new record for a Shift Location within another table. The EditShift method however, only updates the Shift record, but it does not update the Shift Location record even though I have assigned the shiftID and the new locationID.

Any info on how to correct this would be much appreciated.

Thank you.

EDIT

My ShiftLocation class is as follows

public partial class ShiftLocation
{
    public int shiftLocationID { get; set; }
    public int shiftID { get; set; }
    public int locationID { get; set; }

    public virtual Shift Shift { get; set; }
}

The UpdateShift method within the ShiftService class is as follows

public void UpdateShift(Shift item)
    {
        _UoW.Shifts.Update(item);
        _UoW.Commit();
    }

And this then calls the Update method in my Generic Repository

public void Update(TEntity entityToUpdate)
    {
        dbSet.Attach(entityToUpdate);
        context.Entry(entityToUpdate).State = EntityState.Modified;
    }

2nd Edit

Following on from Slauma's answer I edited my EditShift Post Action to the following

if (ModelState.IsValid)
            {
                //Shift shift = new Shift();
                Shift shift = _shiftService.GetShiftByID(model.shiftID);
                ShiftLocation shiftLocation = shift.Locations.Where(s => s.shiftID == model.shiftID).Single();

                shift = Mapper.Map<ViewModelShift, Shift>(model);

                shiftLocation.locationID = model.locationID;
                shift.Locations.Add(shiftLocation);

                _shiftService.UpdateShift(shift);

                return RedirectToAction("Index");
            }

My problem now is that when Update Method in my Generic Repository is called, the following error occurs

An object with the same key already exists in the ObjectStateManager. 
The ObjectStateManager cannot track multiple objects with the same key

Now, I now why this is happening, because in my EditPost action I am retrieving an instance of the Shift, then in the Update Method in the Generic Repository I am trying to attach the same Shift.

I am just getting really confused now. My Generic Repositro looks fine as I copied it from the Microsoft MVC tutorial mentioned at the top of this post.

Again any help on how to get this simple update working would be much appreciated.

tcode
  • 5,055
  • 19
  • 65
  • 124
  • Can you show the `ShiftLocation` class and the code inside of `_shiftService.UpdateShift(shift)`? – Slauma Apr 03 '12 at 18:11
  • What exactly do you want to achieve? Imagine the `shift` is stored in the DB and already has 5 `ShiftLocations` assigned to it in the DB. Now you reach the `EditShift` post action. In your code you create a `ShiftLocation` object and add it to the `shift.Locations` collection. Do you want now: 1) Add this new location as number 6 to the already existing locations, or 2) Do you want to delete the 5 existing locations and replace it with the new one, or 3) Do you want find the location as one of the 5 (by Id?) and then update it with the new values ? – Slauma Apr 03 '12 at 20:49
  • @Slauma - When I reach the 'EditShift' post action, I want to update the 'Shift' with the new details which are retrieved from the passed in 'ViewModelShift model'. This ViewModel will also contain the 'locationID' for only **1** 'ShiftLocation', however, this ShiftLocation already exists in the database, I just wish to update it with the new locationID. Does this make sense? Thanks. – tcode Apr 05 '12 at 09:23
  • @Slauma - Could it be that the related ShiftLocation needs to be loaded, ie, attached to the Shift before the update statement can happen? – tcode Apr 05 '12 at 09:54
  • I think you should save your `location` object, not the `shift`. – Gert Arnold Apr 05 '12 at 09:54
  • @GertArnold - The problem seems to be that when the ViewModelShift is passed back to the 'EditShift' post action, it contains values for shiftID and locationID, however, it does not contain a value for shiftLocationID. I believe this is the reason why the Location is not updated. However, I don't know how to get the shiftLocationID as the user only selects the locationID from a drop down list. – tcode Apr 05 '12 at 11:22

1 Answers1

1

Refering to your comment...

When I reach the 'EditShift' post action, I want to update the 'Shift' with the new details which are retrieved from the passed in 'ViewModelShift model'. This ViewModel will also contain the 'locationID' for only 1 'ShiftLocation', however, this ShiftLocation already exists in the database, I just wish to update it with the new locationID.

... I would try this (omitting your repository structure):

[HttpPost]
public ActionResult EditShift(ViewModelShift model)
{
    if (ModelState.IsValid)
    {
        Shift shift = context.Shifts
            .Include(s => s.Locations)
            .Single(s => s.shiftID == model.shiftID);

        context.Entry(shift).CurrentValues.SetValues(model);

        ShiftLocation location = shift.Locations.Single();
        // because you expect exactly one location

        location.locationID = model.locationID;

        context.SaveChanges();

        return RedirectToAction("Index");
    }

    //...
}

Setting the state of the shift to Modified does not work because it doesn't affect any related entities. The location would still be in state Unchanged. You could also set the state for the location to Modified, but it looks like you don't have the primary key property shiftLocationID in your ViewModel. So, the only way to find the correct location to update is loading it via the navigation property of the shift (=Include in the example above).

Edit

The code in your 2nd Edit doesn't work because AutoMapper creates a new Instance of shift and later you attach this shift to the context. But since you already have loaded the shift from the database, this shift is attached to the context as well. You cannot attach two different instances with the same key to the context. This causes the exception.

My code above should work, I try to rewrite it using your service and generic repository. Both must be extended because service and repository don't seem to be rich enough in functions to perform the task. Especially the generic Update is too weak to update an object graph (root object + one or multiple navigation properties).

[HttpPost]
public ActionResult EditShift(ViewModelShift model)
{
    if (ModelState.IsValid)
    {
        Shift shift = Mapper.Map<ViewModelShift, Shift>(model);
        _shiftService.UpdateShiftAndLocation(shift, model.LocationID);

        return RedirectToAction("Index");
    }

    //...
}

Create a new method in the service:

public void UpdateShiftAndLocation(Shift detachedShift, int locationID)
{
    Shift attachedShift = _UoW.Shifts.Find(
        s => s.ShiftID == detachedShift.ShiftID, s => s.Locations);

    _UoW.Shifts.UpdateFlatProperties(attachedShift, detachedShift);

    ShiftLocation location = attachedShift.Locations.Single();
    // MUST be exactly one location for the Shift in the DB
    // ToDo: Catch the case somehow, if there is no or more than one location
    location.LocationID = locationID;

    _UoW.Commit();
}

Find method in your generic repository:

public IQueryable<T> Find(Expression<Func<T, bool>> predicate,
    params Expression<Func<T, object>>[] includes)
{
    return dbSet.IncludeMultiple(includes)
        .Where(predicate);
}

(Use Ladislav's IncludeMultiple extension method of IQueryabe<T> from here: https://stackoverflow.com/a/5376637/270591)

UpdateFlatProperties method in your generic repository:

// "Flat" means: Scalar and Complex properties, but not Navigation properties
public void UpdateFlatProperties(T attachedEntity, T detachedEntity)
{
    context.Entry(attachedEntity).CurrentValues.SetValues(detachedEntity);
}
Community
  • 1
  • 1
Slauma
  • 175,098
  • 59
  • 401
  • 420
  • Please see my 2nd Edit above. Any more idea's? Thanks. – tcode Apr 05 '12 at 11:50
  • @tgriffiths: Can you double check the code in your 2nd edit? Somehow it doesn't make sense: You are adding `shiftLocation` to the `shift.Locations` collection, but retrieved this `shiftLocation` from exactly the same collection before. Also, you instantiate a new `location`, but do nothing with this instance. – Slauma Apr 05 '12 at 12:01
  • I removed the instantiation 'location, as it wasn't doing anything. I am adding 'shiftLocation' to shift.Locations because my AutoMapper does not do this for me. Once the Mapper.Map code runs, shift.Locations = 0, therefore I add the shiftLocation with the newly updated 'locationID' to shift.Locations. The problem still occurs though, ie, key already exists in the ObjectStateManager when doing an update. – tcode Apr 05 '12 at 13:14
  • I really appreciate your work on this. Your new edit looks good, I'll implement that into my solution. Thanks. – tcode Apr 05 '12 at 14:53