Reputation: 415
I am working on a project with a DbContext class generated from an EDMX file. I need to filter some of the records based on authentication status in some situations and rather than rewrite the code to filter the records after receiving them from the DbContext class I at first assumed it would be simple to create another class which inherits from the original DbContext class and then override the getters and setters, then use the new class instead. Something like this:
public partial class AutogeneratedBaseClass : DbContext
{
...
public virtual DbSet<Record> Records { get; set; }
...
}
public class ChildClass : AutogeneratedBaseClass
{
...
public override DbSet<Record> Records
{
get {
return (DbSet<Record>) base.Records.Where(...);
}
set {}
}
}
This compiles fine but when I run it base is null and debugging yields "error CS0175: Use of keyword 'base' is not valid in this context."
Is there anyway to accomplish this? Or do I need to look for another solution? Thanks!
Upvotes: 1
Views: 1395
Reputation: 486
Probably best to use composition over inheritance like so:
Implement the DbContext
public class MainDbContext : DbContext
{
public DbSet<Record> Records { get;set; }
}
Then implement the filtered version
public class FilteredDbContext
{
private readonly MainDbContext dbContext;
public FilteredDbContext(MainDbContext dbContext)
{
this.dbContext = dbContext;
}
public IQueryable<Record> Records
{
get { return dbContext.Records.Where(...); }
}
}
Ideally, there should also be interfaces for both, so you don't depend directly on the concrete classes.
Upvotes: 1