You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
iot/projects/IoT.Shared/Areas/Admin/Controlls/Users/UserController.cs

64 lines
2.1 KiB

using Application.Domain.Entities;
using Application.Models;
using Infrastructure.Application;
using Infrastructure.Data;
using Infrastructure.Extensions;
using Infrastructure.Web.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq;
namespace IoT.Shared.Areas.Admin.Controllers
{
[ApiExplorerSettings(IgnoreApi = false)]
[Authorize]
[Area(nameof(Admin))]
public class UserController : CrudController<User, PagedListModel<EditUserModel>, EditUserModel, EditUserModel>
{
private readonly RoleController _ajax;
public UserController(IRepository<User> repo, RoleController ajax) : base(repo)
{
this._ajax = ajax;
}
public override IQueryable<User> Include(IQueryable<User> query)
{
return query.Include(o => o.UserRoles).ThenInclude(o => o.Role);
}
public override void ToDisplayModel(User entity, EditUserModel model)
{
model.Roles = entity.UserRoles.Select(o => o.RoleId).ToList();
entity.UserRoles.ForEach(o => ViewData.Add(o.RoleId, o.Role.Name));
}
public override void ToEditModel(User entity, EditUserModel model)
{
if (entity != null)
{
model.Roles = entity.UserRoles.Select(o => o.RoleId).ToList();
}
this.ViewData.MultiSelectList(o => model.Roles, () => this._ajax.GetRoleMultiSelectList(model.Roles));
}
public override void ToEntity(EditUserModel model, User entity)
{
foreach (var id in entity.UserRoles.Select(o => o.RoleId).ToList())
{
if (!model.Roles.Any(o => o == id))
{
entity.UserRoles.RemoveAll(o => o.RoleId == id);
}
}
foreach (var id in model.Roles)
{
if (!entity.UserRoles.Any(o => o.RoleId == id))
{
entity.UserRoles.Add(new UserRole { RoleId = id });
}
}
}
}
}