Exemple #1
0
        public async Task EditRoleIds(long userId, long[] roleIds)
        {
            using (var db = new WeixinDbContext())
            {
                CommonService <User> userCs = new CommonService <User>(db);
                var user = await userCs.GetById(userId);

                if (user == null)
                {
                    throw new ArgumentException("用户不存在" + userId);
                }
                user.Roles.Clear();//先清空用户的角色

                CommonService <Role> roleCs = new CommonService <Role>(db);
                //寻找数据库里的roleId和传入的roleId的交集
                var roles = await roleCs.GetAll().Where(r => roleIds.Contains(r.Id)).ToArrayAsync();

                foreach (var role in roles)
                {
                    user.Roles.Add(role);//重新添加角色
                }
                await db.SaveChangesAsync();
            }
        }