Question

We've been building an application which has 2 parts. Server Side: A WCF service, Client Side: A WPF app following MVVM patterns

So we also use Self Tracking Entities to get some database job done but we're having struggles.

Here's an example code:

public bool UpdateUser(User userToUpdate)
{
    using (DBContext _context = new DBContext())
    {
        try
        {
            userToUpdate.MarkAsModified();
            _context.Users.ApplyChanges(userToUpdate);
            _context.SaveChanges();
            return true;
        }
        catch (Exception ex)
        {
            // LOGS etc.
            return false;
        }
    }
}

So when I call this function from the client, it gives us this exception:

AcceptChanges cannot continue because the object's key values conflict with another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.

"User" entity has one "many-to-1..0 (UserType)" and five "0..1-to-many" associations. And that "UserType" has a "many-to-many (Modules)" association.

When we send a User instance to this function, UserType is included with it's Modules.

If you can guide me through solving this problem, that'd be great.

Thank you.

Was it helpful?

Solution

This is how I resolved this issue as a reference for the others having the same issue with me.

public bool UpdateUser(User userToUpdate)
{
    using (DBContext _context = new DBContext())
    {
        try
        {
            User outUser = usersModel.Users.Single(x => x.UserId == userToUpdate.UserId);
            outUser = userToUpdate;
            _context.ApplyCurrentValues("Users", outUser);
            _context.SaveChanges();
            return true;
        }
        catch (Exception ex)
        {
            // LOGS etc.
            return false;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top