我是ASP.NET MVC的新手。我正在使用工作单元和存储库来进行数据访问。目前,代码直接使用域模型来访问数据库。我一直试图让ViewModel(SystemAdminViewModel)与Generic Repository而不是Model进行交互。怎么可能?
以下是代码的样子:
控制器/ 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 / DineMonsterDBContext.cs
public class DineMonsterDBContext : DbContext
{
public DbSet<SystemAdmin> SystemAdmins { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<SystemAdmin>();
}
}
DAL / UnitOfWork.cs
public class UnitOfWork : IDisposable
{
private DineMonsterDBContext context = new DineMonsterDBContext();
private GenericRepository<SystemAdmin> systemAdminRepository;
private GenericRepository<SystemAdminViewModel> systemAdminVMRepository;
public GenericRepository<SystemAdmin> SystemAdminRepository
{
get
{
if (this.systemAdminRepository == null)
{
this.systemAdminRepository = new GenericRepository<SystemAdmin>(context);
}
return systemAdminRepository;
}
}
DAL / GenericRepository.cs
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);
}
}
DAL / IGenericRepository.cs
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();
}
模型/ SystemAdminViewModel.cs
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;
}
}
答案 0 :(得分:0)
您必须创建一个方法,将SystemAdmin映射到SystemAdminViewModel或使用像automapper这样的库,并在您的控制器中使用它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);
}