2012-10-30 55 views
1

我試圖與實體框架的通用倉庫來工作並在下面這段代碼就來了:通用倉庫構造

public class GenericRepository<TContext, TEntity> : IGenericRepository<TEntity> 
where TContext : IUnitOfWork 
where TEntity : class 
{ 
protected TContext _context; 
/// <summary> 
/// Constructor that takes a context 
/// </summary> 
/// <param name="context">An established data context</param> 
public GenericRepository(TContext context) 
{ 
    _context = context; 
} 

public IQueryable<TEntity> Select() 
{ 
    return _context.Set<TEntity>().AsQueryable(); 
} 

public IEnumerable<TEntity> GetAll() 
{ 
    return _context.Set<TEntity>().AsEnumerable(); 
} 

public IEnumerable<TEntity> Where(Func<TEntity, bool> predicate) 
{ 
    return _context.Set<TEntity>().Where(predicate); 
} 

public TEntity GetSingle(Func<TEntity, bool> predicate) 
{ 
    return _context.Set<TEntity>().Single(predicate); 
} 

public TEntity GetFirst(Func<TEntity, bool> predicate) 
{ 
    return _context.Set<TEntity>().First(predicate); 
} 

public void Add(TEntity entity) 
{ 
    if (entity == null) 
     throw new ArgumentException("Cannot add a null entity"); 

    _context.Set<TEntity>().Add(entity); 
} 

public void Delete(TEntity entity) 
{ 
    if (entity == null) 
     throw new ArgumentException("Cannot delete a null entity"); 

    _context.Set<TEntity>().Remove(entity); 
} 

public void Attach(TEntity entity) 
{ 
    if (entity == null) 
     throw new ArgumentException("Cannot attach a null entity"); 

    _context.Set<TEntity>().Attach(entity); 
} 

#region IDisposable implementation 
private bool disposedValue; 

public void Dispose(bool disposing) 
{ 
    if (!this.disposedValue) 
    { 
     if (disposing) 
     { 
      // dispose managed state here if required 
     } 
     // dispose unmanaged objects and set large fields to null 
    } 
    this.disposedValue = true; 
} 

public void Dispose() 
{ 
    Dispose(true); 
    GC.SuppressFinalize(this); 
} 
#endregion 
} 

但是我覺得有點難以理解創建的構造需要

/// <summary> 
/// Constructor that takes a context 
/// </summary> 
/// <param name="context">An established data context</param> 
public GenericRepository(TContext context) 
{ 
    _context = context; 
} 

有人可以解釋一下這個用法嗎?

感謝

回答

2

這是因爲有可能是在您的項目多的DbContext類,所以你需要注入特定的DbContext實例來告訴它的DbContext您正在使用的GenericRepository類。

你需要有多種的DbContext類的原因可能是:

  1. 你的項目目標的多個數據庫;

  2. 您的項目很大,考慮到性能和可維護性,您希望將其分成幾個模塊。例如:

    public class BaseContext<TContext> : DbContext 
        where TContext : DbContext, new()   
    {   
        protected BaseContext() 
        : base("name=ConnectionString") 
        {    
        } 
    } 
    
    public class ShopDbContext :BaseContext<ShopDbContext> 
    { 
        public DbSet<Product> Products{ get; set; } 
    } 
    
    public class BlogDbContext :BaseContext<BlogDbContext> 
    { 
        public DbSet<Blog> Blogs{ get; set; } 
    } 
    

現在,如果你要查詢的產品,你必須實例化ShopDbContext,並把它傳遞到GenericRepository構造反轉(IoC是一個不錯的選擇)。

+0

非常感謝你....我現在明白了:) – RAHUL