简体   繁体   English

ASP.NET 5 MVC 6和Entity Framework 7问题

[英]ASP.NET 5 MVC 6 and Entity Framework 7 issues

We can't add Owin and Entity framework 7 together. 我们不能将Owin和Entity框架7加在一起。 As we do so then there will be ambiguity between Microsoft.AspNet.Identity.core 2.0.0.0 and Microsoft.AspNet.Identity 3.0.0 Beta1 当我们这样做时,Microsoft.AspNet.Identity.core 2.0.0.0和Microsoft.AspNet.Identity 3.0.0 Beta1之间将存在歧义。

And hence I am not able to implement role provider in my application to manage the user roles. 因此,我无法在我的应用程序中实现角色提供程序来管理用户角色。

After facing this issue I removed Owin references and created UserManager using Microsoft.AspNet.Identity 3.0.0 and EF 7 but UserManager.AddToRoleAsync(user, roleName) always throws exception as below:- 在遇到此问题后,我删除了Owin引用并使用Microsoft.AspNet.Identity 3.0.0和EF 7创建了UserManager,但UserManager.AddToRoleAsync(user,roleName)始终抛出异常,如下所示: -

InvalidOperationException: The instance of entity type 'Mozaics.DAL.Models.ApplicationUser' cannot be tracked because another instance of this type with the same key is already being tracked. InvalidOperationException:无法跟踪实体类型“Mozaics.DAL.Models.ApplicationUser”的实例,因为已经跟踪了具有相同键的此类型的另一个实例。 For new entities consider using an IIdentityGenerator to generate unique key values. 对于新实体,请考虑使用IIdentityGenerator生成唯一键值。

Code snippet is like this. 代码片段是这样的。

 public async Task<ActionResult> RoleAddToUser(string UserName, string RoleName)
    {
        var user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

        var result = await UserManager.AddToRoleAsync(user,  RoleName );

        ViewBag.ResultMessage = "Role created successfully !";
        var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
        ViewBag.Roles = list;

        return View("ManageUserRoles");
    }

@sanjaypujari @sanjaypujari

Just try that one: 试试那个:

var user = await context.FindByNameAsync(UserName);
ApplicationUser appuser = (ApplicationUser)user;
var result = await UserManager.AddToRoleAsync(appuser,  RoleName);

When executed like this, ApplicationUser shouldn't be tracked twice. 执行此操作时,不应跟踪ApplicationUser两次。 Same thing helps, too, if you want to update a ApplicationUser. 如果您想更新ApplicationUser,同样的事情也有帮助。

I run to this issue. 我遇到了这个问题。 One solution that worked for me was that getting the user via the UserManager and then adding the role: 一个对我有用的解决方案是通过UserManager获取用户,然后添加角色:

instead of 代替

var user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var result = await UserManager.AddToRoleAsync(user,  RoleName );

use the following 使用以下内容

var user = await UserManager.FindByNameAsync(UserName);
var result = await UserManager.AddToRoleAsync(user,  RoleName );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM