我是 Entity Framework 的新手,并加入了一个使用通用存储库的项目,如下所示。存储库的设置方式有什么缺点吗?我注意到大多数教程都描述了基于通用基础存储库创建多个存储库,而不是拥有一个处理所有内容的通用存储库。
提供一些背景知识,此代码是 ASP.NET MVC 3 网站的一部分,我们使用 unity 作为 IOC 容器。业务层中的所有组件都继承自一个基类,该基类通过构造函数注入了 IEntityRepository。
这是通用存储库类
public class MyRepository
{
private const string containerName = "myEntities";
private readonly ObjectContext context;
private readonly Hashtable objectSets;
// Track whether Dispose has been called.
private bool disposed;
public MyRepository()
{
string connectionString = ConfigurationManager.ConnectionStrings[containerName].ConnectionString;
context = new ObjectContext(connectionString) {DefaultContainerName = containerName};
context.ContextOptions.LazyLoadingEnabled = true;
context.ContextOptions.ProxyCreationEnabled = true;
objectSets = new Hashtable();
}
private ObjectSet<TEntity> GetObjectSet<TEntity>() where TEntity : class
{
ObjectSet<TEntity> objectSet;
var type = typeof (TEntity);
if (objectSets.ContainsKey(type))
{
objectSet = objectSets[type] as ObjectSet<TEntity>;
}
else
{
objectSet = context.CreateObjectSet<TEntity>();
objectSets.Add(type, objectSet);
}
return objectSet;
}
public IQueryable<TEntity> GetAll<TEntity>(params string[] entities) where TEntity : class
{
ObjectQuery<TEntity> objectQuery = GetObjectSet<TEntity>();
foreach (var entity in entities)
{
objectQuery = objectQuery.Include(entity);
}
return objectQuery;
}
public void Insert<TEntity>(TEntity entity) where TEntity : class
{
ObjectSet<TEntity> objectSet = GetObjectSet<TEntity>();
objectSet.AddObject(entity);
}
public void Update<TEntity>(TEntity entity) where TEntity : class
{
ObjectSet<TEntity> objectSet = GetObjectSet<TEntity>();
EntityKey key = objectSet.Context.CreateEntityKey(objectSet.EntitySet.Name, entity);
object originalItem;
if (objectSet.Context.TryGetObjectByKey(key, out originalItem))
{
objectSet.ApplyCurrentValues(entity);
}
else
{
objectSet.Attach(entity);
objectSet.ApplyCurrentValues(entity);
}
}
public void Delete<TEntity>(TEntity entity) where TEntity : class
{
ObjectSet<TEntity> objectSet = GetObjectSet<TEntity>();
objectSet.DeleteObject(entity);
}
public void SaveChanges()
{
try
{
context.SaveChanges();
}
catch (Exception ex)
{
ex.ToString();
throw ex;
}
}
public void Dispose()
{
Dispose(true);
// Take yourself off the Finalization queue
// to prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called
if (!disposed)
{
if (disposing)
{
context.Dispose();
}
}
disposed = true;
}
~MyRepository()
{
Dispose(false);
}
}
这是用于公开方法的接口:
public interface IEntityRepository : IDisposable
{
void Delete<TEntity>(TEntity entity) where TEntity : class;
IQueryable<TEntity> GetAll<TEntity>(params string[] entities) where TEntity : class;
void Insert<TEntity>(TEntity entity) where TEntity : class;
void Update<TEntity>(TEntity entity) where TEntity : class;
void SaveChanges();
}