2014-02-21 44 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) 
     { 

     } 

}