当 EF 没有引入 UserRoles Table 时,如何添加要使用的角色?

How to add a role to use when EF doesn't bring in UserRoles Table?

我有一个 UserRoles table,只有两列 userId 和 RoleId,entityframework 没有把 class 带进来。如何在没有用户角色的情况下保存关联 class?

我在EntityFramework中的用户和角色class是这样的。

public partial class aspnet_Users
{
    public aspnet_Users()
    {
        this.aspnet_Roles = new HashSet<aspnet_Roles>();
    }

    public System.Guid ApplicationId { get; set; }
    public System.Guid UserId { get; set; }
    public string UserName { get; set; }
    public string LoweredUserName { get; set; }
    public string MobileAlias { get; set; }
    public bool IsAnonymous { get; set; }
    public System.DateTime LastActivityDate { get; set; }

    public virtual aspnet_Applications aspnet_Applications { get; set; }
    public virtual aspnet_Membership aspnet_Membership { get; set; }
    public virtual ICollection<aspnet_Roles> aspnet_Roles { get; set; }
}

    public partial class aspnet_Roles
    {
        public aspnet_Roles()
        {
            this.aspnet_Users = new HashSet<aspnet_Users>();
        }

        public System.Guid ApplicationId { get; set; }
        public System.Guid RoleId { get; set; }
        public string RoleName { get; set; }
        public string LoweredRoleName { get; set; }
        public string Description { get; set; }

        public virtual aspnet_Applications aspnet_Applications { get; set; }
        public virtual ICollection<aspnet_Users> aspnet_Users { get; set; }
    }

EF 没有在模型中给我 UserRoles class,但它显示在 XML.

当我尝试添加新用户时,我是这样访问的

                    var role = new Data.aspnet_Roles();
                    role.RoleId = userItem.roles.First().RoleId;
                    role.RoleName = userItem.roles.First().RoleName;
                    user.aspnet_Roles.Add(role);

这给出了一个错误

InnerException {"Cannot insert duplicate key row in object 'dbo.aspnet_Roles' with unique index 'aspnet_Roles_index1'.\r\nThe statement has been terminated."} System.Exception {System.Data.SqlClient.SqlException}

这里的答案表明它应该有效。我不知道我做错了什么。 Entity Framework Add User to Role

我得到这个错误也是有道理的。但是我对如何在没有用户角色 EF class 的情况下存储用户角色关系一无所知。我真的卡住了。任何帮助表示赞赏。谢谢。

你做这项工作的方式,你正在创建一个新角色,它具有与现在数据库中相同的 ID 和名称,因为你正在使用上下文中不存在的角色实例,这样, context认为是一个新角色,应该加入。

您应该告知上下文这不是一个新角色,这样做:

  • 您可以使用查询将您需要的角色加载到您将用于保存用户的相同上下文中

  • 或者您可以将角色对象附加(输入)到您将用于保存用户的同一上下文,并将其状态设置为未更改。

比如你可以先找到你想要的角色:

 var db= new YourContext();
 var role = db.aspnet_Roles.Where(....).FirstOrDefault();

然后使用角色实例和上下文实例:

 user.aspnet_Roles.Add(role);
 db.SaveChanges();