Nick Chambers
Nick Chambers

Reputation: 181

Foreign keys updating on creation but not on edit

In my application, users are able to be assigned roles. In the setup page for this, I have the following code:

foreach (string userRole in roleArray)
{
    OrganizationRole orgRole = signedUpOrg.Roles.FirstOrDefault(target => target.Name == userRole && target.OrganizationId == signedUpOrg.OrganizationId);
    if (orgRole != null)
    {
        OrganizationUser_OrganizationRole existingUserRole = orgRole.OrganizationUser_OrganizationRole.FirstOrDefault(target => target.Organization_User.User.UserId    == orgUser.User.UserId &&
                                                                                                                                target.OrganizationRole.Name            == userRole && 
                                                                                                                                target.OrganizationRole.OrganizationId  == signedUpOrg.OrganizationId);

        if (existingUserRole == null || orgUser.User.UserId == 0) // new user role to new users or existing users with new roles
        {
            orgRole.OrganizationUser_OrganizationRole.Add(new OrganizationUser_OrganizationRole
            {
                Organization_User   = orgUser,
                OrganizationRole    = orgRole
            });
        }
    }
}

With this, we are able to cycle through the roles which are to be assigned and save them in the database. This works perfectly fine on creating the user and their roles, but on editing there is no change. The code seems to be hit at all the crucial points with the correct data (roles, etc) but there is no reflection in the database or on the front end.

This code is in a method called SaveUsers in a class called CommonUtilities and is called in an AdministrationController with the following code:

CommonUtilities.SaveUsers(viewModel);

Can anyone possibly think of any reasons as to why this would work correctly on creation but not while editing? Many thanks in advance and I will be more than willing ot clarifiy on any points.

Upvotes: 1

Views: 67

Answers (1)

JTMon
JTMon

Reputation: 3199

A similar issue drove me to choose NHibernate over EF as it can update children and grandchildren collections (probably even deeper levels but I have not tried that). Adjusting ObjectState like the answers referred to by @JhonatasKleinkauff seemed the only answer in EF but was not satisfactory in our case. This seems to only happen when you disconnect from the ObjectContext between retrieval and saving the parent object.

Upvotes: 1

Related Questions