Asp.net mvc 如何在ASP.NET MVC中将存储库(DAL/UnitOfWork.cs)映射到ViewModel?

Asp.net mvc 如何在ASP.NET MVC中将存储库(DAL/UnitOfWork.cs)映射到ViewModel?,asp.net-mvc,repository,mapping,viewmodel,Asp.net Mvc,Repository,Mapping,Viewmodel,我是ASP.NETMVC新手。我使用工作单元和存储库进行数据访问。目前代码直接使用域模型访问数据库。我一直在尝试使ViewModelSystemAdminViewModel与通用存储库而不是模型交互。怎么可能呢 下面是代码的样子: 控制器/SystemAdminController.cs public class SystemAdminController : Controller { private UnitOfWork unitOfWork = new UnitOfWork();

我是ASP.NETMVC新手。我使用工作单元和存储库进行数据访问。目前代码直接使用域模型访问数据库。我一直在尝试使ViewModelSystemAdminViewModel与通用存储库而不是模型交互。怎么可能呢

下面是代码的样子:

控制器/SystemAdminController.cs

public class SystemAdminController : Controller
{

    private UnitOfWork unitOfWork = new UnitOfWork();

    //
    // GET: /SystemAdmin/
    public ViewResult Index()
    {
        //Constant for System Admin List
        ViewBag.Title = Settings.Default.SystemAdminList;
        var systemAdmin = unitOfWork.SystemAdminRepository.Get().ToList();
        return View(systemAdmin);
    }

    //
    // GET: /SystemAdmin/Details/5
    public ViewResult Details(int id)
    {
        SystemAdmin systemAdmin = unitOfWork.SystemAdminRepository.GetByID(id);
        return View(systemAdmin);
    }

    //
    // GET: /SystemAdmin/Create
    public ActionResult Create()
    {
        //Constant for System Admin List
        ViewBag.Title = Settings.Default.AddSystemAdmin;
        ViewBag.BackToList = Settings.Default.BackToSystemAdminList;
        ViewBag.AddTitle = Settings.Default.AddSystemAdmin;

        return View();
    }

    //
    // POST: /SystemAdmin/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(
        [Bind(Include = "ID,Username,Password,Status")]
     SystemAdmin systemAdmin)
    {
        //Constant for System Admin List
        ViewBag.Title = Settings.Default.AddSystemAdmin;
        ViewBag.BackToList = Settings.Default.BackToSystemAdminList;
        ViewBag.AddTitle = Settings.Default.AddSystemAdmin;

        try
        {
            if (ModelState.IsValid)
            {
                unitOfWork.SystemAdminRepository.Insert(systemAdmin);
                unitOfWork.Save();
                return RedirectToAction("Index");
            }
        }
        catch (DataException /* dex */)
        {
            //Log the error (uncomment dex variable name after DataException and add a line here to write a log.)
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
        }
        return View(systemAdmin);
    }

    //
    //GET: SystemAdmin/Edit/5
    public ActionResult Edit(int id)
    {
        //Constant for System Admin List
        ViewBag.EditTitle = Settings.Default.EditSystemAdmin;
        ViewBag.BackToList = Settings.Default.BackToSystemAdminList;

        SystemAdmin systemAdmin = unitOfWork.SystemAdminRepository.GetByID(id);
        return View(systemAdmin);
    }

    //
    //POST: SystemAdmin/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(
         [Bind(Include = "ID,Username,Password,Status")]
     SystemAdmin systemAdmin)
    {
        //Constant for System Admin List
        ViewBag.EditTitle = Settings.Default.EditSystemAdmin;
        ViewBag.BackToList = Settings.Default.BackToSystemAdminList;

        try
        {
            if (ModelState.IsValid)
            {
                unitOfWork.SystemAdminRepository.Update(systemAdmin);
                unitOfWork.Save();
                return RedirectToAction("Index");
            }
        }
        catch (DataException /* dex */)
        {
            //Log the error (uncomment dex variable name after DataException and add a line here to write a log.)
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
        }
        return View(systemAdmin);
    }

    //
    // GET: /SystemAdmin/Delete/5
    public ActionResult Delete(int id)
    {
        SystemAdmin systemAdmin = unitOfWork.SystemAdminRepository.GetByID(id);
        return View(systemAdmin);
    }

    //
    // POST: /SystemAdmin/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        SystemAdmin systemAdmin = unitOfWork.SystemAdminRepository.GetByID(id);
        unitOfWork.SystemAdminRepository.Delete(id);
        unitOfWork.Save();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        unitOfWork.Dispose();
        base.Dispose(disposing);
    }

}
DAL/dbcontext.cs

public class DineMonsterDBContext : DbContext
{
    public DbSet<SystemAdmin> SystemAdmins { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<SystemAdmin>();
    }
}

您必须创建一个将SystemAdmin映射到SystemAdminViewModel的方法,或者在控制器中使用类似于和的库,并从它使用loke

public ViewResult Index()
{
    //Constant for System Admin List
    ViewBag.Title = Settings.Default.SystemAdminList;
    var systemAdmin = unitOfWork.SystemAdminRepository.Get().ToList();
    var systemAdminVM=Mapper.Map<SystemAdmin ,SystemAdminViewModel>(systemAdmin);//your mapper usage
    return View(systemAdmin);
}

既然你是新来的,请允许我帮你省去一些痛苦。扔掉所有存储库和工作单元垃圾。我想你是从ASP.NET网站上得到的,但是尽管有源代码,这不是一个好方法。类似ORM的实体框架是您的工作单元,每个数据库集都是一个存储库。您所做的只是添加一个额外的层,它什么也不做,只需要更多的维护、额外的测试,等等,而没有任何好处。
public class GenericRepository<TEntity> where TEntity : class
{
    internal DineMonsterDBContext context;
    internal DbSet<TEntity> dbSet;

    public GenericRepository(DineMonsterDBContext context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }

    public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }

    public virtual TEntity GetByID(object id)
    {
        return dbSet.Find(id);
    }

    public virtual void Insert(TEntity entity)
    {
        dbSet.Add(entity);
    }

    public virtual void Delete(object id)
    {
        TEntity entityToDelete = dbSet.Find(id);
        Delete(entityToDelete);
    }

    public virtual void Delete(TEntity entityToDelete)
    {
        if (context.Entry(entityToDelete).State == EntityState.Detached)
        {
            dbSet.Attach(entityToDelete);
        }
        dbSet.Remove(entityToDelete);
    }

    public virtual void Update(TEntity entityToUpdate)
    {
        dbSet.Attach(entityToUpdate);
        context.Entry(entityToUpdate).State = EntityState.Modified;
    }
}
    public GenericRepository<SystemAdminViewModel> SystemAdminVMRepository
    {
        get
        {

            if (this.systemAdminVMRepository == null)
            {
                this.systemAdminVMRepository = new GenericRepository<SystemAdminViewModel>(context);
            }
            return systemAdminVMRepository;
        }
    }

    public void Save()
    {
        context.SaveChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
public interface IGenericRepository<T> where T : class
{
    IEnumerable<T> Get();
    T GetByID(object id);
    void Insert(T obj);
    void Delete(object id);
    void Update(T obj);
    void Save();
}
public class SystemAdminViewModel
{
    public int ID { get; set; }

    [Required]
    [StringLength(20, ErrorMessage = "Username can contain only 20 characters")]
    [Display(Name = "Username")]
    public string Username { get; set; }

    [Required]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Required]
    [Compare("Password", ErrorMessage = "Password does not match")]
    public string ConfirmPassword { get; set; }

    public int Status { get; set; }

    public SystemAdminViewModel()
    {
        this.Status = 1;
    }
}
public ViewResult Index()
{
    //Constant for System Admin List
    ViewBag.Title = Settings.Default.SystemAdminList;
    var systemAdmin = unitOfWork.SystemAdminRepository.Get().ToList();
    var systemAdminVM=Mapper.Map<SystemAdmin ,SystemAdminViewModel>(systemAdmin);//your mapper usage
    return View(systemAdmin);
}