DBContext Inherit from multiple base class

Tim Cadieux 21 Reputation points
2022-08-19T16:59:44.02+00:00

I have just implemented the DuendeIdentity Server and by DBContext looks like this.

public class DataContext : ApiAuthorizationDbContext<ApplicationUser>  
{  
    public DataContext(  
        DbContextOptions options,  
        IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions)  
    {  
    }  
 ...  

I now wish to implement some basic Database Auditing which I have successfully done in the past using this https://codewithmukesh.com/blog/audit-trail-implementation-in-aspnet-core/ however it is implemented in this way

public abstract class AuditableIdentityContext : IdentityDbContext  
{  
    public AuditableIdentityContext(DbContextOptions options) : base(options)  
    {  
    }   

With the DataContext then inheriting from it like

public partial class DataContext : AuditContext  
{  
    public DataContext(DbContextOptions<DataContext> options)  
        : base(options)  
    {  
    }  

I am trying to understand how I may use the two together. Any help would be appreciated.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
696 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 47,716 Reputation points
    2022-08-19T17:37:17.127+00:00

    C# does not support multiple inheritance by design so you cannot inherit from both. You'll have to move the logic from one to the other type.

    Just taking a quick look at the link you provided it doesn't really need a base type. It can work with any DbContext implementation. All you need to do is move the "generate the audit" logic into an extension method off of DbContext. Now it is reusable anywhere. Then override your SaveChangesAsync method in your actual DbContext and call the extension method.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Tim Cadieux 21 Reputation points
    2022-08-19T18:08:50.117+00:00

    Would you have an example of 'move the "generate the audit" logic into an extension method off of DbContext' that I might take a look at? I'm not usually the backend guy so a lot of this stuff is new to me.

    Thx for the reply