2014-02-21 54 views
0

我在我的应用程序中使用了MVC模式。对于每个模型类我都有一个控制器。所有控制器类都有一个saveOrUpdate()方法。我想知道这是否足以创建定义所述方法的接口,然后所有控制器都实现它。控制器执行的接口使用

请注意saveOrUpdate()收到一个模型类作为参数。所以它会像UserController#saveOrUpdate(User user),CourseController#saveOrUpdate(Course course),AppleManager#saveOrUpdate(Apple apple)

回答

1

我想你需要的是实现一个给定的实体通用功能的通用存储库。我最近开始在我的MVC项目中实施Repository Pattern以及Unit of Work。这是我如何做到这一点。

MyDbContext.cs:

public class MyDbContext : DbContext 
    { 
     public MyDbContext() : base("name=DefaultConnection”) 
     { 
     } 

     public System.Data.Entity.DbSet<User> Users { get; set; } 
     public System.Data.Entity.DbSet<Course> Courses { get; set; } 

    } 

工作单位:

public class UnitOfWork : IUnitOfWork 
    { 
     //private variable for db context 
     private MyDbContext _context; 
     //initial db context variable when Unit of Work is constructed 
     public UnitOfWork() 
     { 
      _context = new MyDbContext(); 
     } 
     //property to get db context 
     public MyDbContext Context 
     { 
      //if not null return current instance of db context else return new 
      get { return _context ?? (_context = new MyDbContext()); } 
     } 
     //save function to save changes using UnitOfWork 
     public void Save() 
     { 
      _context.SaveChanges(); 
     } 
    } 

通用存储库:

public class RepositoryBase<T> : IRepositoryBase<T> where T : class 
    { 
     protected readonly IUnitOfWork _unitOfWork; 
     private readonly IDbSet<T> _dbSet; 

     public RepositoryBase(IUnitOfWork unitOfWork) 
     { 
      _unitOfWork = unitOfWork; 
      _dbSet = _unitOfWork.Context.Set<T>(); 
     } 

    public virtual void Save() 
     { 
      _unitOfWork.Save(); 
     } 

     public virtual void Add(T entity) 
     { 
      _dbSet.Add(entity); 
      _unitOfWork.Save(); 
     } 
    //Similarly you can have Update(), Delete(), GetAll() implementation here 

    } 

实体库从通用回购继承:

public class UserRepository:RepositoryBase<User>,IUserRepository 
    { 
     public UserRepository(IUnitOfWork unitOfWork) : base(unitOfWork) 
     { 
     } 
    //Here you can also define functions specific to User 
    } 

控制器:

public class UserController : Controller 
    { 
     private readonly IUserRepository _dbUserRepository; 

     public UserController(IUserRepository dbUserRepository) 
     { 
      _dbUserRepository = dbUserRepository; 
     } 

     // GET: /User/ 
     public ActionResult Index() 
     { 
     var users = _dbUserRepository.GetAll(); 

      return View(users.ToList()); 
     } 
} 
1

在你的控制器实现,现在创建一个接口

interface ISave 
{ 
     void Save(object obj); 
} 

public class AppleControler : Controller , ISave 
{ 

     public void Save(Object obj) 
     { 
       //you can cast your object here. 

     } 

} 

选择二

interface ISave<T> 
{ 
     void Save(T obj); 
} 


public class AppleControler : Controller , ISave<Apple> 
{ 

     public void Save(Apple obj) 
     { 

     } 

}