通用存储库和通用DbContext中没有隐式引用转换错误

时间:2015-08-18 12:37:01

标签: c# generics inheritance interface

我在程序中使用通用存储库,但是当我将上下文描述为通用上下文时,它会导致错误:

  

错误1类型   'ArchiveBoundedContext.Infrastructure.Contexts.ArchiveBoundedContext'   不能在泛型类型中用作类型参数'TContext'   方法'SharedKernel.Infrastructure.Repository'。    没有隐式参考转化   'ArchiveBoundedContext.Infrastructure.Contexts.ArchiveBoundedContext'   'System.Data.Entity.DbContext'。   f:\上一版本的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);
    }
}

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; }
}

1 个答案:

答案 0 :(得分:1)

Repository课程中,替换DbContext的{​​{1}}:

class

这有用吗?