我正在使用使用实体框架6的asp.net vmc5 Web应用程序。现在,我正在尝试使它们工作:-
定义通用存储库。
为每种DBSet类型创建一个专用存储库,该存储库将从通用存储库派生。
为每个专用存储库创建一个接口。
使用UnitOfwork类,以便调用多个存储库类将导致生成单个事务。
我有一个DbSet
类型SkillType
。所以我创建了以下界面:
namespace SkillManagementp.DAL
{
public interface ISkillTypeRepository {
}
然后是以下通用存储库:
namespace SkillManagement.DAL
{
public class GenericRepository<TEntity> where TEntity : class
{
internal SkillManagementEntities context;
internal DbSet<TEntity> dbSet;
public GenericRepository(SkillManagementEntities context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}//code goes here...
以下SkillTypeRepository:-
namespace SkillManagement.DAL
{
public class SkillTypeRepository : GenericRepository<SkillType> : ISkillTypeRepository
{
private SkillManagementEntities db = new SkillManagementEntities();
public void Dispose()
{
db.Dispose();
}
public void Save()
{
db.SaveChanges();
}
}
}
最后,我创建了以下UnitOfWork类:
namespace SkillManagement.DAL
{
public class UnitOfWork : IDisposable
{
private SkillManagementEntities db = new SkillManagementEntities();
private SkillTypeRepository skillTypeRepository;
public SkillTypeRepository SkillTypeRepository
{
get
{
if (this.skillTypeRepository == null)
{
this.skillTypeRepository = new SkillTypeRepository();
}
return skillTypeRepository;
}
}
public void Save()
{
db.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
db.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
但是我遇到了这些错误:
我无法为我的SkillManagmentRepositry类定义两个派生类。
我也在SkillTypeRepository内收到此错误:-SkillManagement.DAL.GenericRepository'不包含带有0个参数的构造函数
重写SkillTypeRepository
为:
public class SkillTypeRepository : GenericRepository<SkillType>, ISkillTypeRepository
{
public SkillTypeRepository() : base(new SkillManagementEntities())
{
}
//rest of code etc
}
正如我在评论中提及了,你SkillTypeRepository
没有一个构造函数,但GenericRepository
确实,作为基类有一个构造函数,你需要提供一个派生类和呼叫:base(params)
看到这里了解更多详情。
然后,您可以简单地调用base.context
以获得对的引用SkillManagementEntities
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句