1

在我的应用程序中,可以为用户分配角色。在此设置页面中,我有以下代码:

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
            });
        }
    }
}

有了这个,我们可以循环访问要分配的角色并将它们保存在数据库中。这在创建用户及其角色时非常有效,但在编辑时没有任何变化。代码似乎在所有关键点都被正确的数据(角色等)击中,但在数据库或前端没有反映。

此代码位于名为 CommonUtilities 的类中名为 SaveUsers 的方法中,并在 AdministrationController 中使用以下代码调用:

CommonUtilities.SaveUsers(viewModel);

谁能想到为什么这会在创建时正常工作但在编辑时不能正常工作的任何原因?提前非常感谢,我非常愿意澄清任何问题。

4

1 回答 1

1

一个类似的问题促使我选择 NHibernate 而不是 EF,因为它可以更新子孙集合(可能更深层次,但我没有尝试过)。像@JhonatasKleinkauff 提到的答案一样调整 ObjectState 似乎是 EF 中的唯一答案,但在我们的案例中并不令人满意。这似乎只发生在您在检索和保存父对象之间与 ObjectContext 断开连接时。

于 2013-05-10T13:58:55.353 回答