在通用存储库和通用DbContext中没有隐式引用转换错误
本文关键字:引用 错误 转换 存储 DbContext | 更新日期: 2023-09-27 18:08:25
我在程序中使用通用存储库,但当我将上下文描述为通用上下文时,它会导致错误:
错误1类型"ArchiveBoundedContext.Infrastructure.Contexts.ArchiveBoundedContext"不能用作泛型类型or中的类型参数 'TContext' 方法"SharedKernel.Infrastructure.Repository"。没有从的隐式引用转换"ArchiveBoundedContext.Infrastructure.Contexts.ArchiveBoundedContext""System.Data.Entity.DbContext"。f:'Last Version Of Projects'Archiver-master'SharedKernel.Infrastructure'bin'Debug'SharedKernel.Infrastructure.dllArchiveBoundedContext。应用
通用库:
public abstract class Repository<TEntity, TContext>
where TEntity : class
where TContext : DbContext, new()
{
private DbSet<TEntity> _set;
public TContext ActiveContext { get; set; }
protected Repository()
{
ActiveContext = new TContext();
}
public DbSet<TEntity> Set
{
get { return _set ?? (_set = ActiveContext.Set<TEntity>()); }
}
public TEntity Create()
{
return Set.Create();
}
public int Add(TEntity item)
{
Set.Add(item);
return ActiveContext.SaveChanges();
}
public int Remove(TEntity item)
{
Set.Remove(item);
return ActiveContext.SaveChanges();
}
public int Update()
{
return ActiveContext.SaveChanges();
}
}
ArchiveRepository:
public class ArchiveRepository : Repository<PersonIdentificationImage, Contexts.ArchiveBoundedContext>, IArchiveRepository
{
public ArchiveRepository() { }
public void AddPersonIdentificationImage(PersonIdentificationImage personIdentificationImage)
{
var ctx = ActiveContext;
ctx.PersonIdentificationImages.Add(personIdentificationImage);
}
}
ArchiveService:
public class ArchiveService : IArchiveService
{
private readonly ArchiveRepository _archiveRepository;
public ArchiveService()
{
_archiveRepository = new ArchiveRepository();
}
}
QTasArchiveBaseContext:
public class QTasArchiveBaseContext<TContext> : DbContext where TContext : DbContext
{
static QTasArchiveBaseContext()
{
Database.SetInitializer<TContext>(null);
}
protected QTasArchiveBaseContext()
: base(DatabaseSettings.Default.QTasArchiveDatabaseConString)
{ }
}
ArchiveBoundedContext:
public class ArchiveBoundedContext : QTasArchiveBaseContext<ArchiveBoundedContext>
{
public DbSet<PersonOtherImage> PersonScannedImages { get; set; }
public DbSet<PersonIdentificationImage> PersonIdentificationImages { get; set; }
}
在Repository
类中,将class
替换为DbContext
:
public abstract class Repository<TEntity, TContext>
where TEntity : class
where TContext : DbContext, new()
public abstract class Repository<TEntity, TContext>
where TEntity : class
where TContext : class
{
private DbSet<TEntity> _set;
public TContext ActiveContext { get; set; }
public Repository(TContext dbContext)
{
ActiveContext = dbContext;
}
....
}
可以吗?