【发布时间】:2017-04-19 20:28:56
【问题描述】:
我的问题来自这里,
我已经为国家存储库编写了一个接口,并且我正在使用 UnitOfWork 跟踪通用存储库,我还使用 ninject 进行 DI
public interface ICountryRepository : IRepository<Country>
{
List<Country> GetAll();
}
实施国家资料库接口,
public class CountryRepository : BaseRepository<Country>, ICountryRepository
{
public CountryRepository(DbContextcontext) : base(context)
{
}
public List<Country> GetAll(){
// Not implemented
}
}
ICountryRepository 接口中还有一个额外的方法,我也实现了。但是当我需要使用 UnitOfWork 使用该方法时,我不能使用该方法。那是给 System.NullReferenceException
我试过了,
ICountryRepository repository = UnitOfWork.Repository<Country>() as ICountryRepository;
return repository.GetAll();
向下转换建议该方法,但没有转换该方法是不可访问。
给出了附加代码,
实体
基础实体
public class BaseEntity
{
public int Id { get; set; }
}
产品实体
public class Country : BaseEntity
{
public string Name { get; set; }
}
存储库
界面
public interface IRepository<T>
{
void Add(T entity);
}
基础存储库
public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
{
protected IDbContext _context;
private readonly IDbSet<TEntity> _dbEntitySet;
private bool _disposed;
public BaseRepository(IDbContext context)
{
_context = context;
_dbEntitySet = _context.Set<TEntity>();
}
public void Add(TEntity entity)
{
_context.SetAsAdded(entity);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (!_disposed && disposing)
{
_context.Dispose();
}
_disposed = true;
}
}
工作单元
界面
public interface IUnitOfWork : IDisposable
{
IRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity;
void BeginTransaction();
int Commit();
Task<int> CommitAsync();
void Rollback();
void Dispose(bool disposing);
}
实施的工作单元
public class UnitOfWork : IUnitOfWork
{
private readonly IDbContext _context;
private bool _disposed;
private Hashtable _repositories;
public UnitOfWork(IDbContext context)
{
_context = context;
}
public IRepository<TEntity> Repository<TEntity>() where TEntity : BaseEntity
{
if (_repositories == null)
{
_repositories = new Hashtable();
}
var type = typeof(TEntity).Name;
if (_repositories.ContainsKey(type))
{
return (IRepository<TEntity>)_repositories[type];
}
var repositoryType = typeof(BaseRepository<>);
_repositories.Add(type, Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), _context));
return (IRepository<TEntity>)_repositories[type];
}
/* Other Implementation
*
*
*
*/
}
【问题讨论】:
-
可能在这一行:
_context.Set<TEntity>()。您正在传递BaseProduct,它不是一个实体,然后EF 无法创建DBSet。UnitOfWork.Repository<Country>应该可以,但UnitOfWork.Repository<BaseProduct>不行。 -
我已经编辑过了,不幸的是这不是问题所在。我仍然面临@smoksnes 的问题
-
似乎没有实现
IBaseProductRepository,因此您的演员阵容将始终为空。另外,使用Activator有什么特别的原因吗?没有什么魔法发生。你应该可以使用new BaseRepository<TEntity>(_context)。 -
@smoksnes,我改变了这个错误。我正在使用 Ninject 进行依赖注入,它正在发挥作用。但是问题还是没有解决。
标签: c# asp.net-mvc entity-framework repository-pattern unit-of-work