【发布时间】:2015-08-18 12:37:00
【问题描述】:
我在我的程序中使用了通用存储库,但是当我将上下文描述为通用上下文时,它会导致错误:
错误 1 类型 'ArchiveBoundedContext.Infrastructure.Contexts.ArchiveBoundedContext' 不能用作类型参数 '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.dll ArchiveBoundedContext.Application
通用存储库:
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);
}
}
存档服务:
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; }
}
【问题讨论】:
-
ArchiveBoundedContext.Infrastructure.Contexts.ArchiveBoundedContext的定义在哪里? -
@David 将 ArchiveBoundedContext 添加到我的问题末尾。
-
还有...
QTasArchiveBaseContext<T>是什么?根据错误ArchiveBoundedContext不能用作DbContext。应该吗? -
@David 我在我的问题中描述了 ArchiveBoundedContext。它在 ArchiveBoundedContext 之前。公共类 QTasArchiveBaseContext
: DbContext where TContext : DbContext { } -
为什么你的存储库继承自 IEnumerable?
标签: c# generics inheritance interface