EF核心插入多对多表

时间:2019-04-03 10:47:51

标签: c# asp.net-core razor-pages ef-core-2.0

我用Razor Pages架起了我的User模型,并在创建页面上想在联结表UserRoles上插入用户角色。

这是我的模特

[Table("Users")]
public class User
{
    public User()
    {
        IsActivo = true;          
    }

    public int Id { get; set; }

    [Required]
    [Display(Prompt = "Username")]
    public string Username { get; set; }
    [Display(Name = "Último Acesso")]
    public DateTime? DataSessao { get; set; }
    [Display(Name = "Activo")]
    public bool IsActivo { get; set; } 
    public Colaborador Colaborador { get; set; }

    public ICollection<UserRoles> UserRoles { get; set; }
}

这是创建模型

public class CreateModel : PageModel
{
    private readonly HutIS.Models.HutISContext _context;

    public CreateModel(HutISContext context)
    {
        _context = context;
    }

    public IActionResult OnGet()
    {
        DepartamentosOptions = _context.Departamento.Select(d =>
              new SelectListItem
                  {
                       Value = d.Id.ToString(),
                       Text = d.Nome
                  }).ToList();


        RolesOptions = _context.Roles.Select(d =>
                  new SelectListItem
                      {
                         Value = d.Id.ToString(),
                         Text = d.Type
                       }).ToList();

        return Page();
    }

    [BindProperty]
    public User User { get; set; }
    public List<SelectListItem> DepartamentosOptions { get; set; }
    public List<SelectListItem> RolesOptions { get; set; }

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.User.Add(User);

        await _context.SaveChangesAsync();

        return RedirectToPage("./Index");
    }
}

在HTML上

<div class="form-group">
    <label asp-for="User.UserRoles" class="control-label"></label>
    <select asp-for="User.UserRoles" asp-items="Model.RolesOptions" class="form-control form-control-sm">
        <option value="">Selecione um Departamento...</option>
    </select>
    <span asp-validation-for="User.UserRoles" class="text-danger"></span>
</div>

我不确定我该怎么做,当然我会在这里遇到异常,但是如果UserRoles是User中的一个集合,该如何绑定UserRoles?

编辑

我解决了异常问题,它与模型属性有关。现在的问题是,在UserRoles表上没有插入任何内容,我不太确定该怎么做,因为与部门相比,User的UserRoles没有导航属性。

enter image description here

如您所见,关系是正确的

1 个答案:

答案 0 :(得分:1)

对于<select multiple="multiple" asp-for="User.RoleIds" asp-items="Model.RolesOptions" class="form-control form-control-sm">,它将提交RoleId值而不是Role Object,您需要定义public ICollection<int> UserRoleIds { get; set; }来接受RoleId。

请按照以下步骤操作:

  1. 使用UserRoleIds定义一个ViewModel

    public class UserVM
    {
        public UserVM()
        {
            IsActivo = true;
        }
    
        public int Id { get; set; }
    
        [Required]
        [Display(Prompt = "Username")]
        public string Username { get; set; }
        [Display(Name = "Último Acesso")]
        public DateTime? DataSessao { get; set; }
        [Display(Name = "Activo")]
        public bool IsActivo { get; set; }
    
        public ICollection<int> RoleIds { get; set; }
    }
    
  2. 剃刀模型

    public class CreateModel : PageModel
    {
        private readonly TestRazorContext _context;
    
        public CreateModel(TestRazorContext context)
        {
            _context = context;
        }
    
        public IActionResult OnGet()
        {
            RolesOptions = _context.Role.Select(d =>
                    new SelectListItem
                    {
                        Value = d.Id.ToString(),
                        Text = d.Type
                    }).ToList();
            return Page();
        }
    
        [BindProperty]
        public UserVM User { get; set; }
        public List<SelectListItem> RolesOptions { get; set; }
    
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
            //create user
            var user = new User {
                Username = User.Username,
                //rest properties
            };
            _context.User.Add(user);
            await _context.SaveChangesAsync();
            //set user role
            var userRoles = new List<UserRoles>();
            foreach (var roleId in User.RoleIds)
            {
                userRoles.Add(new UserRoles
                {
                    UserId = user.Id,
                    RoleId = roleId
                });
            }
            _context.UserRole.AddRange(userRoles);
            await _context.SaveChangesAsync();
            return RedirectToPage("./Index");
        }
    }
    
  3. 剃刀视图

    <form method="post">
        <div class="form-group">
            <label asp-for="User.Username" class="control-label"></label>
            <input asp-for="User.Username" />
        </div>    
        <div class="form-group">
            <label asp-for="User.RoleIds" class="control-label"></label>
            <select multiple="multiple" asp-for="User.RoleIds" asp-items="Model.RolesOptions" class="form-control form-control-sm">
                <option value="">Selecione um Departamento...</option>
            </select>
            <span asp-validation-for="User.RoleIds" class="text-danger"></span>
        </div>
        <input type="submit" value="Submit"/>
    </form>