Example #1
0
        public async Task AddOrUpdate(UserViewModel user)
        {
            var ex = await _db.Include(u => u.RoleToUsers).ThenInclude(r => r.Role).SingleOrDefaultAsync(u => u.UserId == user.UserId);

            if (ex == null)
            {
                var usr = new User()
                {
                    Username = user.Username,
                    Name     = user.Name,
                    Vorname  = user.Vorname,
                    Password = user.Password,
                };

                List <RoleToUser> rtus = new List <RoleToUser>();
                foreach (var role in user.Roles)
                {
                    var _rtu = new RoleToUser()
                    {
                        Role = role != -1 ? _context.Roles.First(r => r.UserRoleType == (UserRoleType)role) : _context.Roles.First(r => r.UserRoleType == UserRoleType.Default),
                        User = usr
                    };
                    rtus.Add(_rtu);
                    _context.RoleToUsers.Add(_rtu);
                }
                usr.RoleToUsers = rtus;
            }
            else
            {
                _delRoles(ex);
                ex.Name     = user.Name;
                ex.Vorname  = user.Vorname;
                ex.Username = user.Username;
                List <RoleToUser> rtus = new List <RoleToUser>();
                foreach (var role in user.Roles)
                {
                    var _rtu = new RoleToUser()
                    {
                        Role = role != -1 ? _context.Roles.First(r => r.UserRoleType == (UserRoleType)role) : _context.Roles.First(r => r.UserRoleType == UserRoleType.Default),
                        User = ex
                    };
                    rtus.Add(_rtu);
                    _context.RoleToUsers.Add(_rtu);
                }
                ex.RoleToUsers = rtus;
            }

            try
            {
                _context.SaveChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Example #2
0
        internal static void Create(DataContext context, UserRoleType[] roles, User user)
        {
            //user.Roles = context.Roles.Where(r => roles.Contains(r.UserRoleType)).ToList();

            foreach (var role in roles)
            {
                var rtu = new RoleToUser();

                var ro = context.Roles.First(r => r.UserRoleType == role);

                rtu.Role = ro;
                rtu.User = user;

                context.RoleToUsers.Add(rtu);
            }

            context.SaveChanges();
        }