1

我正在将我的 crud 操作从控制器移动到存储库中。

如何将视图包信息从存储库传递到控制器,然后再传递到视图?

我的控制器在存储库中调用 PopulateAssigneUserData

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WWW.Models;
using WWW.DAL;
using WWW.ViewModels;

namespace WWW.Controllers
{ 
    public class RolesController : Controller
    {
        private Iaspnet_RolesRepository aspnet_RolesRepository;

        public RolesController()
        {
            this.aspnet_RolesRepository = new Aspnet_RolesRepository(new WorldofWarCraftContext());
        }

        public RolesController(Iaspnet_RolesRepository aspnet_RolesRepository)
        {
            this.aspnet_RolesRepository = aspnet_RolesRepository;
        }


        //
        // GET: /Roles/Edit/5

        public ActionResult Edit(Guid id)
        {
            aspnet_Roles aspnet_Role = db.aspnet_Roless        
            .Include(i => i.aspnet_User)
            .Where(i => i.RoleId == id)
            .Single();

            PopulateAssigneUserData(aspnet_Role);
            return View(aspnet_Role);
        }

我的存储库有过去存在于控制器中的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using WWW.Models;
using WWW.ViewModels;

namespace WWW.DAL
{
    public class Aspnet_RolesRepository : Iaspnet_RolesRepository, Iaspnet_UsersRepository , IDisposable
    {
        private WorldofWarCraftContext context;

        public Aspnet_RolesRepository(WorldofWarCraftContext context)
        {
            this.context = context;
        }

        public IEnumerable<aspnet_Roles> GetRoles()
        {
            return context.aspnet_Roless.ToList();
        }

        public aspnet_Roles GetRolesByID(Guid id)
        {
            return context.aspnet_Roless.Find(id);
        }


        private void PopulateAssigneUserData(aspnet_Roles aspnet_Role)
        {
            var allUsers = context.aspnet_Users;
            var rolesUsers = new HashSet<Guid>(aspnet_Role.aspnet_User.Select(c => c.UserId));
            var viewModel = new List<AssigneUserData>();
            foreach (var User in allUsers)
            {
                viewModel.Add(new AssigneUserData
                {
                    UserId = User.UserId,
                    UserName = User.UserName,
                    Assigned = rolesUsers.Contains(User.UserId)
                });
            }
            ViewBag.Users = viewModel;
        }
4

1 回答 1

0

你在这里混合了责任。存储库不应与视图模型和 ViewBag 一起使用。存储库应返回域模型。控制器负责将这些域模型映射到视图模型并将这些视图模型传递给视图。此PopulateAssigneUserData方法不应存在于您的存储库中。在您的存储库中,您应该有一个方法可以返回aspnet_Role给定 id 的实例(您当前在 Edit 操作中拥有的代码)。

于 2012-07-08T17:54:57.207 回答