Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7737291
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T07:57:30+00:00 2026-06-01T07:57:30+00:00

I am developing an ASP.Net MVC 3 Web application using Entity Framework 4.1, however,

  • 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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T07:57:32+00:00Added an answer on June 1, 2026 at 7:57 am

    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);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am developing an ASP.Net MVC 3 Web application using Entity Framework 4.1 and
I'm developing a web application using ASP.NET MVC 3 and Entity Framework Code First
I am developing an ASP.Net MVC 3 Web application with Entity Framework 4.1 and
I am developing a web application using Asp.net mvc framework with concept of sub
I'm developing a web application using ASP.NET MVC (I'm new to the framework and
I have started developing a full-web application by using the ASP .NET MVC 3
I'm developing an web application using asp.net MVC and jQuery. I have in my
I have just started developing a full-web application by using the ASP .NET MVC
I'm developing a web application using ASP .NET MVC 1.0 and jQuery (including the
I am developping a web application by using the ASP .NET MVC 3 framework.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.