如何使用trackerenableddbcontext在asp.net mvc5和代码中的实体框架中实现审计跟踪

Posted

技术标签:

【中文标题】如何使用trackerenableddbcontext在asp.net mvc5和代码中的实体框架中实现审计跟踪【英文标题】:How to implement audit trail in asp.net mvc5 and entity-framework in code first, using trackerenableddbcontext 【发布时间】:2019-12-02 12:47:03 【问题描述】:

我正在使用实体框架和代码优先迁移开发 MVC5 应用程序,我想实施审计跟踪。我发现了一个名为 trackerenableddbcontext 的 NuGet 包,看起来很容易使用。但是,我确实安装了该软件包,并执行了以下代码,但仍然没有将任何内容添加到审计表中。

我已经实现了继承自Tracker Context,如代码所示

DBContext class
public class SIContext : TrackerContext //DbContext

    public SIContext()
        : base("name=SIConnectionString")
    
    


    public virtual DbSet<Role> Roles  get; set; 
    public virtual DbSet<User> Users  get; set; 
    public virtual DbSet<Menu> Menus  get; set; 
    public virtual DbSet<MenuPermission> MenuPermissions  get; set; 
    public virtual DbSet<ProductCategory> ProductCategorys  get; set; 
    public virtual DbSet<Product> Products  get; set; 
    public virtual DbSet<Tax> Taxs  get; set; 
    public virtual DbSet<ProductStock> ProductStocks  get; set; 
    public virtual DbSet<PaymentMode> PaymentModes  get; set; 
    public virtual DbSet<Sale> Sales  get; set; 
    public virtual DbSet<InvoiceItems> InvoiceItemss  get; set; 
    public virtual DbSet<Setting> Settings  get; set; 
    public virtual DbSet<InvoiceFormat> InvoiceFormats  get; set; 
    public virtual DbSet<InventoryType> InventoryTypes  get; set; 
    public virtual DbSet<Purchase> Purchases  get; set; 
    public virtual DbSet<Transaction> Transactions  get; set; 
    public virtual DbSet<Invoice> Invoices  get; set; 
    public virtual DbSet<LedgerAccount> LedgerAccounts  get; set; 
    public virtual DbSet<Warehouse> Warehouses  get; set; 
    public virtual DbSet<DuePayment> DuePayments  get; set; 
    public virtual DbSet<Expense> Expenses  get; set; 
    public virtual DbSet<DeliveryNote> DeliveryNotes  get; set; 
    public virtual DbSet<GRV> GRVs  get; set; 
    public virtual DbSet<Artisans> Artisans  get; set; 
    public virtual DbSet<JobCard> JobCards  get; set; 
    public virtual DbSet<Order> Orders  get; set; 
    public virtual DbSet<InternalRequisitionForm> InternalRequisitionForms  get; set; 
    public virtual DbSet<JobRequisition> JobRequisitions  get; set; 
    public virtual DbSet<Stores> Stores  get; set; 
    public virtual DbSet<Machine> Machines  get; set; 
    public virtual DbSet<ListItems> listitem  get; set; 
    public virtual DbSet<JobCardServices> JobCardServices  get; set; 
    public virtual DbSet<JobCardMaterials> JobCardMaterials  get; set; 
    public virtual DbSet<JobRequisitionMaterials> JobRequisitionMaterials  get; set; 
    public virtual DbSet<JobRequisitionServices> JobRequisitionServices  get; set; 
    public virtual DbSet<GRVMaterials> GRVMaterials  get; set; 
    public virtual DbSet<Quotation> Quotations  get; set; 
    public virtual DbSet<QuotationItems> QuotationItems  get; set; 
    public virtual DbSet<DNoteMaterial> DNoteMaterials  get; set; 
    public virtual DbSet<InvoiceMaterials> InvoiceMaterial  get; set; 






    //
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    

        modelBuilder.Configurations.Add(new ShopMate.Maping.RoleMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.UserMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.MenuMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.MenuPermissionMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.ProductCategoryMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.ProductMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.TaxMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.ProductStockMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.PaymentModeMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.SaleMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.InvoiceItemsMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.SettingMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.InvoiceFormatMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.InventoryTypeMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.PurchaseMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.TransactionMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.InvoiceMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.LedgerAccountMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.WarehouseMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.DuePaymentMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.ExpenseMap());
        modelBuilder.Configurations.Add(new ShopMate.Maping.InternalRequisitionFormMap());



        base.OnModelCreating(modelBuilder);
    



我要跟踪的表

[TrackChanges]
public class Product

    [DisplayName("S.No")] 
    public int Id  get; set; 
    [Required]
    [StringLength(100)] 
    [DisplayName("Name")] 
    public string Name  get; set; 
    [Required]
    [DisplayName("Product Category")] 
    public int? ProductCategoryId  get; set; 
    public virtual ProductCategory ProductCategory_ProductCategoryId  get; set; 
    [StringLength(100)] 
    [DisplayName("Bar Code")] 
    public string BarCode  get; set; 
    [Required]
    [DisplayName("Purchase Price")] 
    public Decimal PurchasePrice  get; set; 
    [Required]
    [DisplayName("Sale Price")] 
    public Decimal SalePrice  get; set; 
    [DisplayName("Product Image")] 
    public string ProductImage  get; set; 
    [DisplayName("Added By")] 
    public Nullable<int> AddedBy  get; set; 
    [DisplayName("Date Added")] 
    public Nullable<DateTime> DateAdded  get; set; 
    [DisplayName("Modified By")] 
    public Nullable<int> ModifiedBy  get; set; 
    [DisplayName("Date Modied")] 
    public Nullable<DateTime> DateModied  get; set; 
    [Required]
    [DisplayName("Is Active")] 
    public bool IsActive  get; set; 
    [Required]
    [DisplayName("Stock Alert")] 
    public int StockAlert  get; set; 
    [DisplayName("Tax")] 
    public Nullable<int> TaxId  get; set; 
    [Required]
    [DisplayName("Warehouse")] 
    public int WarehouseId  get; set; 

    [DisplayName("Discount")]
    public Nullable<Decimal> Discount  get; set; 

    [DisplayName("Remaining Quantity")]
    public Nullable<Decimal> RemainingQuantity  get; set; 

    [DisplayName("Remaining Amount")]
    public Nullable<Decimal> RemainingAmount  get; set; 

    [StringLength(100)]
    [DisplayName("HSN")]
    public string HSN  get; set; 

    public virtual ICollection<ProductStock> ProductStock_ProductIds  get; set; 
    public virtual ICollection<Sale> Sale_ProductIds  get; set; 
    public virtual ICollection<InvoiceItems> InvoiceItems_ProductIds  get; set; 
    public virtual ICollection<Purchase> Purchase_ProductIds  get; set; 

控制器功能

[HttpPost]
   [ValidateAntiForgeryToken]
   [ValidateInput(false)]
    public ActionResult Edit(Product ObjProduct, HttpPostedFileBase ProductImage, string HideImage1)
    
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        int userId = Convert.ToInt32(Env.GetUserInfo("userid"));
        try
        

            if (ModelState.IsValid)
            
                if (ProductImage != null)
                
                    var fileName = MicrosoftHelper.MSHelper.StarkFileUploaderCSharp(ProductImage, Server.MapPath("~/Uploads"));
                    ModelState.Clear();
                    ObjProduct.ProductImage = fileName;
                
                else
                
                    ObjProduct.ProductImage = HideImage1;
                


                db.Entry(ObjProduct).State = EntityState.Modified;

                db.SaveChanges(userId);

                sb.Append("Sumitted");
                return Content(sb.ToString());
            
            else
            
                foreach (var key in this.ViewData.ModelState.Keys)
                
                    foreach (var err in this.ViewData.ModelState[key].Errors)
                    
                        sb.Append(err.ErrorMessage + "<br/>");
                    
                
            
        
        catch (Exception ex)
        
            sb.Append("Error :" + ex.Message);
        


        return Content(sb.ToString());

    

我希望它将更改保存到数据库、audidlog 和 auditlogdetails 表中。

【问题讨论】:

【参考方案1】:

当您使用附加实体到 DBContext 时,您需要在应用程序启动时添加 GlobalTrackingConfig.DisconnectedContext = true;

Here is documentation

【讨论】:

以上是关于如何使用trackerenableddbcontext在asp.net mvc5和代码中的实体框架中实现审计跟踪的主要内容,如果未能解决你的问题,请参考以下文章

如何使用本机反应创建登录以及如何验证会话

如何在自动布局中使用约束标识符以及如何使用标识符更改约束? [迅速]

如何使用 AngularJS 的 ng-model 创建一个数组以及如何使用 jquery 提交?

如何使用laravel保存所有行数据每个行名或相等

如何使用 Math.Net 连接矩阵。如何使用 Math.Net 调用特定的行或列?

WSARecv 如何使用 lpOverlapped?如何手动发出事件信号?