0

我想在ASP.NET MVC + EF 4.3項目中實現倉庫模式。EF倉庫模式與ChangeTracker

現在我的DBContext類對SaveChanges有一個覆蓋,它接收一個「userid」參數以執行Audit Trail。

例子:

// This is overridden to prevent someone from calling SaveChanges without specifying the user making the change 
public override int SaveChanges() 
{ 
    throw new InvalidOperationException("User ID must be provided"); 
} 

public int SaveChanges(int userId) 
{ 
    // Get all Added/Deleted/Modified entities (not Unmodified or Detached) 
    foreach (var ent in this.ChangeTracker.Entries().Where(p => p.State ==  System.Data.EntityState.Added || p.State == System.Data.EntityState.Deleted || p.State == System.Data.EntityState.Modified)) 
{ 
        // For each changed record, get the audit record entries and add them 
        foreach (AuditLog x in GetAuditRecordsForChange(ent, userId)) 
        { 
         this.AuditLogs.Add(x); 
        } 
       } 

       // Call the original SaveChanges(), which will save both the changes made and the audit records 
       return base.SaveChanges(); 
      } 

現在,我RepositoryBase類有這樣的事情:

public class RepositoryBase<C> : IDisposable 
     where C : DbContext, new() 
    { 
     private C _DataContext; 

     public virtual C DataContext 
     { 
      get 
      { 
       if (_DataContext == null) 
       { 
        _DataContext = new C(); 
        this.AllowSerialization = true; 
        //Disable ProxyCreationDisabled to prevent the "In order to serialize the parameter, add the type to the known types collection for the operation using ServiceKnownTypeAttribute" error 
       } 
       return _DataContext; 
      } 
     } 

我的問題是我怎麼可以公開我的RepositoryBase類中的方法SaveChanges(int)

任何線索?

回答

1

您將需要在通用定義中使用實際的DbContext而不是DbContext基類。那麼你就可以打電話給你的重寫功能

public class RepositoryBase<C> : IDisposable 
     where C : YourContextClassGoesHere, new() 

{ 
    private C _dataContext; 

    public void SaveChanges() 
    { 
     int userId = GetUserId(); 
     _dataContext.SaveChanges(userId); 
    } 
}