Joshua I. Carter
Joshua I. Carter

Reputation: 35

C# Entity Framework Update SaveChanges() is not updating DB entry

Been working on this C# Entity Framework update problem for a bit now. Maybe one of you can see what I'm missing.

The problem is within the userEntry portion of the code. I've traced through and made sure that userEntry is indeed populated with the information that I intend to update. When entities.SaveChanges(); is invoked, the record is not updated in the database.

            int userId;
            using (Entities entities = new Entities())
            {
                MSIFeedStoreData feedStoreEntry = entities.MSIFeedStoreDatas
                    .FirstOrDefault((d) => d.Alias == user.Alias);

                if (Object.ReferenceEquals(feedStoreEntry, null))
                {
                    throw new ArgumentException("The user's alias could not be located in the feed store. The user cannot be added at this time.");
                }

                int feedStorePersonnelIdValue;
                if (Int32.TryParse(feedStoreEntry.PersonellID, out feedStorePersonnelIdValue))
                {
                    user.EmployeeId = feedStorePersonnelIdValue;
                }
                else
                {
                    throw new ApplicationException("DATABASE BUG CHECK: An entry was found in the feed store for this user but the personnel ID could not be parsed.");
                }

                MSIUser userEntry = entities.MSIUsers
                    .FirstOrDefault((u) => u.EmployeeID == feedStorePersonnelIdValue);

                if (Object.ReferenceEquals(userEntry, null))
                {
                    userEntry = Mapper.Map<MSIUser>(user);
                    userEntry = entities.MSIUsers.Add(userEntry);
                }
                else
                {
                    Mapper.DynamicMap<User, MSIUser>(user, userEntry);
                    entities.MSIUsers.Attach(userEntry);
                }

                userId = userEntry.MSIUser_ID;
                entities.SaveChanges();
            }

            return userId;
        }

Upvotes: 1

Views: 1022

Answers (1)

Charlie Brown
Charlie Brown

Reputation: 2825

Remove the call to Attach, its already attached to the context.

Upvotes: 3

Related Questions