[英]Inheritance and generics in C#
I have the following base repository:我有以下基本存储库:
public abstract class BaseRepository<TEntity, TContext> : IBaseRepository<TEntity>
where TEntity : class
where TContext : ApplicationDbContext
{
// save, add, ...
}
Where IBaseRepository
contains the basic CRUD operations.其中
IBaseRepository
包含基本的 CRUD 操作。
My ApplicationDbContext
is:我的
ApplicationDbContext
是:
public class ApplicationDbContext : IdentityDbContext<IdentityUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
// entities here
}
And finally, AuditableIdentityContext
is used for auditing some tables:最后,
AuditableIdentityContext
用于审计一些表:
public abstract class AuditableIdentityContext : ApplicationDbContext
{
public AuditableIdentityContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public virtual async Task<int> SaveChangesAsync(string userId)
{
// writing to audit log here
OnBeforeSaveChanges(userId);
var result = await base.SaveChangesAsync();
return result;
}
From the repository, I can't access the auditable save method:从存储库中,我无法访问可审核的保存方法:
public class MyRepo : BaseRepository<MyEntity, AuditableIdentityContext>, IMyRepo
{
public MyRepo(AuditableIdentityContext context) : base(context)
{
}
}
Now现在
_myRepo.SaveChangesAsync("123"); // not found
Why I can't access the inherited method from the child class?为什么我不能从子 class 访问继承的方法?
public abstract class BaseRepository<TEntity, TContext> : IBaseRepository<TEntity>
where TEntity : class
where TContext : ApplicationDbContext
{
protected readonly TContext _dbContext;
protected BaseRepository(TContext dbContext)
{
_dbContext = dbContext;
}
}
public class MyRepo : BaseRepository<MyEntity, AuditableIdentityContext>, IMyRepo
{
public MyRepo(AuditableIdentityContext context) : base(context)
{
}
public async Task<int> SaveChangesAsync(string userId)
{
return await _dbContext.SaveChangesAsync(userId);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.