2013-11-09 29 views
2

林不知道我想做什麼是可能的,因爲我還沒有發現任何東西在谷歌和大約30分鐘的密集搜索後,我決定直接問。在存儲庫中實現一個通用類型

我已經definded一個簡單的界面,我的倉庫

public interface IRepository<TEntity> : IDisposable 
{ 
    TEntity GetById(object id); 
    List<TEntity> GetAll(); 
} 

現在我要實現我的第一個存儲庫,它的工作原理是這樣

public class ContentRepository : IRepository<ContentPages> 
{ 
    private readonly Context _db = new Context(); 

    public ContentPages GetById(object id) 
    { 
     var result = _db.ContentPages.Find(id); 
     return result; 
    } 

    public List<ContentPages> GetAll() 
    { 
     return _db.ContentPages.ToList(); 
    } 

    public void Dispose() 
    { 
     _db.Dispose(); 
    } 
} 

這工作得很好,但是當我注入我的存儲庫我的mvc控制器需要一個IRepository<ContentPages>作爲參數類型,我只是想要一個IRepository

我試圖通用型移動到功能本身這樣

public interface IRepository : IDisposable 
    { 
     TEntity GetById<TEntity>(object id); 
     List<TEntity> GetAll<TEntity>(); 
    } 
} 

當我這樣做,我不知道如何在執行我的定義泛型類型TEntity

所以在最後我希望我的使用界面,而無需speficing一個類型,因此它從實際的對象這樣

public constructor1(IRepository ContentRepository){} 

下一個控制器獲取t時的類型他構造

public constructor2(IRepository BlogRepository){} 

我希望我能描述我的問題足夠接近能跟大家瞭解:)

回答

0

在具體實施IRepository類可以定義的類型實例如下。

public TEntity GetById<TEntity>(object id) where TEntity:class 
    { 
    // Implimetation 
    } 

但是在這裏根據存儲庫模式更好地使用如下。

public interface IRepository<TEntity>: IDisposable where TEntity : class 
+0

當我使用第一示例和實施如下: 返回_db.ContentPages.Find(ID); 我得不能轉換ContentPages到TEntity 我不能說Tentity:ContentPages,因爲它違反了接口 – Marvin

0

嘗試這樣的變體:

public interface IRepository<TEntity> where TEntity : class 
{ 
    TEntity Find(params object[] keyValues); 

    // ... 
} 

public class Repository<TEntity> : IRepository<TEntity> where TEntity : class 
{ 
    private readonly IDbSet<TEntity> _dbSet; 

    public Repository(IDbContext context) 
    { 
     _dbSet = context.Set<TEntity>(); 
    } 

    public virtual TEntity Find(params object[] keyValues) 
    { 
     return _dbSet.Find(keyValues); 
    } 

    // ... 
} 

使用示例:

IRepository<ApplicationUser> repository = new Repository<ApplicationUser>(new ApplicationDbContext()); 
ApplicationUser applicationUser = repository.Find("key"); 

此外,還有一個更好的解決方案 - 您可以使用模式的UnitOfWork。檢查this implementation on codeplex。這真的很酷。

實施例:

public class DatabasesController : Controller 
{ 
    private UnitOfWork _unitOfWork; 
    private WebContext _context; 

    public DatabasesController() 
    { 
     _context = new WebContext(); 
     _unitOfWork = new UnitOfWork(_context); 
    } 

    // 
    // GET: /Databases/ 

    public ViewResult Index() 
    { 
     List<Database> databases = 
      _unitOfWork 
      .Repository<Database>() 
      .Query() 
      .Include(database => database.FileEntitiesInfo) 
      .Get() 
      .ToList(); 
     _unitOfWork.Save(); 
     return View(databases); 
    } 
} 
相關問題