Coder Social home page Coder Social logo

bilal-fazlani / tracker-enabled-dbcontext Goto Github PK

View Code? Open in Web Editor NEW
218.0 47.0 110.0 55.99 MB

Tracker-enabled DbContext offers you to implement full auditing in your database

Home Page: https://tracker-enabled-dbcontext.bilal-fazlani.com/

License: Other

C# 76.19% CSS 3.98% HTML 13.80% JavaScript 5.70% Shell 0.30% ASP.NET 0.03%
auditing database logging entity-framework c-sharp

tracker-enabled-dbcontext's Introduction

Tracker-enabled DbContext

Join the chat at https://gitter.im/bilal-fazlani/tracker-enabled-dbcontext Build status Nuget NuGet Pre Release

This library is built on top of entity framework. If offers you to implement full auditing in your application. With the help of this library, we can track all the CRUD operations on database including table names, column names, what was the old value, what's the new value, who changed it, when did it get changed, etc.

It comes with an GNU Lesser General Public License v3.0 Licence.

👉Documentation

tracker-enabled-dbcontext's People

Contributors

ahahcbigeim avatar alexanderlindsay avatar asulwer avatar bilal-fazlani avatar dependabot[bot] avatar excommunicated avatar geertvanhorrik avatar gitter-badger avatar gradu-kpmg avatar jbaig avatar lrfalk01 avatar merlin-taylor avatar mg5283 avatar mgildea avatar mikhail-barg avatar mikhailovenator avatar pablotdv avatar scarlettcode avatar slypete avatar stuartferguson avatar theyo avatar tizzick avatar wshirey avatar yuyuki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tracker-enabled-dbcontext's Issues

Creation of AuditLogDetail Causes Execution of Multiple Database Queries

The following call stack is traced for each property of each modified or deleted entity.

  • LogDetailsAuditor.OriginalValue
  • DbEntryExtensions.GetDatabaseValue
  • DbEntityEntry.GetDatabaseValues

This last method causes Entity Framework to execute a database query. This slows down commits which include a number of deleted/modified rows.

Can't the lock be removed ?

private static TValue GetFromCache<TKey, TValue>(ConcurrentDictionary<TKey, TValue> dictionary, TKey key,
            Func<TValue> func)
        {
            lock (dictionary)
            {
                if (!dictionary.ContainsKey(key))
                {
                    dictionary[key] = func();
                }

                return dictionary[key];
            }
        }

The dictionary is ConcurrentDictionary. Can't the lock be removed ? What could be side-effect of removing lock on a ConcurrentDictionary ? I thought they are thread-safe.

Key problem with fluent configuration.

I like to use fluent configuration on my repositories and I just realised that I have to mark the key property with [Key] attribute, looks like the tracker engine can't find the key without it. =/
Also, it will be nice if we can mark a model class with TrackChanges without using attributes, I kinda like to keep my model as clean as possible. Maybe a fluent configuration or something alike.

TrackerDbContext crashes with complicated EF schema

For some reason in my EF project I get the error below when saving. This doesn't appear if I use EF DbContext instead.
"Sequence contains no matching element"
at System.Linq.Enumerable.Single[TSource](IEnumerable1 source, Func2 predicate)
at TrackerEnabledDbContext.Common.Extensions.TypeExtensions.GetCachedTableName(Type entityType, ITrackerContext context)
at TrackerEnabledDbContext.Common.Extensions.TypeExtensions.<>c__DisplayClassa.b__9(String k)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
at TrackerEnabledDbContext.Common.Extensions.TypeExtensions.GetFromCache[TKey,TVal](ConcurrentDictionary2 dictionary, TKey key, Func2 valueFactory)
at TrackerEnabledDbContext.Common.Extensions.TypeExtensions.GetTableName(Type entityType, ITrackerContext context)
at TrackerEnabledDbContext.Common.LogAuditor.CreateLogRecord(Object userName, EventType eventType, ITrackerContext context)
at TrackerEnabledDbContext.Common.CommonTracker.AuditAdditions(ITrackerContext dbContext, Object userName, IEnumerable1 addedEntries) at TrackerEnabledDbContext.TrackerContext.SaveChanges(Object userName) at MetaDB.Models.MetaDbDataContext.SaveChanges() in c:\Users\niemite\Documents\Visual Studio 2013\Projects\MetaDB\MetaDB\Models\MetaDBDataContext.cs:line 40 at MetaDB.Controllers.ExcelImportController.Index() in c:\Users\niemite\Documents\Visual Studio 2013\Projects\MetaDB\MetaDB\Controllers\ExcelImportController.cs:line 154 at lambda_method(Closure , ControllerBase , Object[] ) at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod() at System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f()

Performance improvement: don't query same value twice

In LogDetailsAuditor value retrievals, you use this code:

 originalValue = _dbEntry.GetDatabaseValues().GetValue<object>(propertyName) == null ? null : _dbEntry.GetDatabaseValues().GetValue<object>(propertyName).ToString();

I recommend that you use this code instead:

var value = _dbEntry.GetDatabaseValues().GetValue<object>(propertyName);
originalValue = (value != null) ? value.ToString() : null;

Changed Table name to TypeFullName breaks physical logging naming

In version 3 you have changed audit table AuditLogs field TableName to TypeFullName. I think it was bad idea. AuditLogs should reflect real table name, not application entity full name. Entity name does not provide value from database perspective. For example,
[TrackChanges]
[Table("dbo.TableName")]
public partial class EntityName {}

Is it possible to configure logger to write TableName (like it was in version 2.7) defined in model attribute rather than TypeFullName like Namespace.Models.EntityName ?

There is no store type corresponding to the conceptual side type 'DateTimeOffset' of primitive type 'DateTimeOffset'.

PM> Add-Migration AddAuditLog
Scaffolding migration 'AddAuditLog'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration AddAuditLog' again.
PM> Add-Migration AddAuditLog
System.NotSupportedException: There is no store type corresponding to the conceptual side type 'DateTimeOffset' of primitive type 'DateTimeOffset'.
at System.Data.Entity.SqlServer.SqlProviderManifest.GetStorePrimitiveTypeIfPostSql9(String storeTypeName, String nameForException, PrimitiveTypeKind primitiveTypeKind)
at System.Data.Entity.SqlServer.SqlProviderManifest.GetStoreType(TypeUsage edmType)
at System.Data.Entity.ModelConfiguration.Edm.Services.StructuralTypeMappingGenerator.MapTableColumn(EdmProperty property, String columnName, Boolean isInstancePropertyOnDerivedType)
at System.Data.Entity.ModelConfiguration.Edm.Services.PropertyMappingGenerator.Generate(EntityType entityType, IEnumerable1 properties, StorageEntitySetMapping entitySetMapping, StorageMappingFragment entityTypeMappingFragment, IList1 propertyPath, Boolean createNewColumn)
at System.Data.Entity.ModelConfiguration.Edm.Services.TableMappingGenerator.Generate(EntityType entityType, DbDatabaseMapping databaseMapping)
at System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.GenerateEntityTypes(DbDatabaseMapping databaseMapping)
at System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.Generate(EdmModel conceptualModel)
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeContext() at System.Data.Entity.Internal.LazyInternalContext.get_ModelBeingInitialized() at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer) at System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter w) at System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action1 writeXml)
at System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext context)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Scaffold(String migrationName, String language, String rootNamespace, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name, Boolean force, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
There is no store type corresponding to the conceptual side type 'DateTimeOffset' of primitive type 'DateTimeOffset'.
PM> Add-Migration AddAuditLog
System.NotSupportedException: There is no store type corresponding to the conceptual side type 'DateTimeOffset' of primitive type 'DateTimeOffset'.
at System.Data.Entity.SqlServer.SqlProviderManifest.GetStorePrimitiveTypeIfPostSql9(String storeTypeName, String nameForException, PrimitiveTypeKind primitiveTypeKind)
at System.Data.Entity.SqlServer.SqlProviderManifest.GetStoreType(TypeUsage edmType)
at System.Data.Entity.ModelConfiguration.Edm.Services.StructuralTypeMappingGenerator.MapTableColumn(EdmProperty property, String columnName, Boolean isInstancePropertyOnDerivedType)
at System.Data.Entity.ModelConfiguration.Edm.Services.PropertyMappingGenerator.Generate(EntityType entityType, IEnumerable1 properties, StorageEntitySetMapping entitySetMapping, StorageMappingFragment entityTypeMappingFragment, IList1 propertyPath, Boolean createNewColumn)
at System.Data.Entity.ModelConfiguration.Edm.Services.TableMappingGenerator.Generate(EntityType entityType, DbDatabaseMapping databaseMapping)
at System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.GenerateEntityTypes(DbDatabaseMapping databaseMapping)
at System.Data.Entity.ModelConfiguration.Edm.Services.DatabaseMappingGenerator.Generate(EdmModel conceptualModel)
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeContext() at System.Data.Entity.Internal.LazyInternalContext.get_ModelBeingInitialized() at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer) at System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter w) at System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action1 writeXml)
at System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext context)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Scaffold(String migrationName, String language, String rootNamespace, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name, Boolean force, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
There is no store type corresponding to the conceptual side type 'DateTimeOffset' of primitive type 'DateTimeOffset'.

Resolving EventType conflict

Our current project has a model called EventType. I know you can use the Fluent API to map table names and column names but I can't seem to get it right with EventType because its an enum and not an entity? Is there a way to get entity framework to differentiate between the two?

"The type 'TrackerEnabledDbContext.Common.Models.EventType' and the type 'MyProject.Common.Models.EventType' both have the same simple name of 'EventType' and so cannot be used in the same model. All types in a given model must have unique simple names. Use 'NotMappedAttribute' or call Ignore in the Code First fluent API to explicitly exclude a property or type from the model."

I would prefer not to have to change mine and migrate data but if that's the only solution I can do that.

Thanks for you excellent work!

Performance improvement: cache LogDetailsAuditor

In the LogDetailsAuditor, the results of GetColumnName should be cached which is a great performance improvement.

Same for LogAuditor.GetTableName(). My recommendation is to extract to extension methods and cache there.

TrackerIdentityContext and IdentityDbContext<ApplicationUser>

Hi bilal-fazlani,

How do i configure "Step 2: Inherit" if i am using the mvc 5 entity framework and the identity framework > 2.0.0?

I using something like this, as you can see i already inherent from IdentityDbContext

file identityModels.cs

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using TrackerEnabledDbContext.Identity; // --> nuget package is installed

namespace MyApplication.Models
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
   {
       public ApplicationDbContext()
          : base("DefaultConnection", throwIfV1Schema: false)
       {
       }

        protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<ApplicationUser>()
                .ToTable("Users", "dbo").Property(p => p.Id).HasColumnName("Id");
            modelBuilder.Entity<IdentityUserRole>()
                .ToTable("UserRoles");
            modelBuilder.Entity<IdentityUserLogin>()
                .ToTable("SystemLogins");
            modelBuilder.Entity<IdentityUserClaim>()
               .ToTable("UserClaims");
            modelBuilder.Entity<IdentityRole>()
               .ToTable("Roles").Property(p => p.Id).HasColumnName("Id");
            modelBuilder.Entity<ApplicationRole>()
                .ToTable("Roles").Property(p => p.Id).HasColumnName("Id");
        }

        static ApplicationDbContext()
        { 
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
}

Demo project fails with Invalid object name 'dbo.SplitString'.

Hi
When I run your demo project it fails with the error message shown below.

I suspect I dont have function on database called 'dbo.SplitString'. When I trying creating one, using samples I found on the internet, it fails with other messages. So can you please explain why Im getting this error.

thanks
Richard

Error message starts here

Server Error in '/' Application.

Invalid object name 'dbo.SplitString'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.SplitString'.

Source Error:

Line 165:
Line 166: // Call the original SaveChanges(), which will save both the changes made and the audit records...Note that added entry auditing is still remaining.
Line 167: int result = await base.SaveChangesAsync(cancellationToken);
Line 168:
Line 169: //By now., we have got the primary keys of added entries of added entiries because of the call to savechanges.

Source File: M:\Downloads\bilal-fazlani-tracker-enabled-dbcontext-v3.4-0-ge978c94\bilal-fazlani-tracker-enabled-dbcontext-e978c94\TrackerEnabledDbContext.Identity\TrackerIdentityContext.cs Line: 167

Must override IdentityUser Id property with [Key]

If I want to track my ASP.net Identity user class, I cannot do so without overriding the standard Id.

The IdentityUser Id property is not marked as [Key] even though it is the primary key for the entity.

So I have to override the Id property like so:

  [Key]
  public override String Id
  {
     get
     {
        return base.Id;
     }
     set
     {
        base.Id = value;
     }
  }

before I can track changes properly. This should work out of the box without overriding the original Id in my opinion.

Why AGPL?

If this code is AGPL, that means that any code I link to it has to be GPL or AGPL. Is it your intention that I cannot use this library with a closed source web app?

Update to version 3.5 dll issues

After update to 3.5 by Nuget, I can see both dlls have the same version 3.5 but when I deploy it to server I can see error caused by dll dependencies:
Could not load file or assembly 'TrackerEnabledDbContext.Common, Version=3.4.5.0, Culture=neutral, PublicKeyToken=4f92af0b908c4a0a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference

It looks like TrackerEnabledDbContext has ref to TrackerEnabledDbContext.Common 3.4.5
I have double checked deployed files versions. Both of them 3.5
There is no dlls in GAC, just in working folder.

I have reinstalled TrackerEnabledDbContext packages, deleted all data from destination folder and redeployed to server again. Now it works. Was is local cache issue?

Navigational property not audited in specific scenario

Navigational Property not audited when its foreignKey property is not changed.

for example

[TrackChanges]
public class ChildModel
{
        [Key]
        public int Id { get; set; }

        public int ParentId { get; set; }

        [ForeignKey("ParentId")]
        public virtual ParentModel Parent { get; set; }
}

in the above code sample,
when parent is changed like this:

Parent parent2 = new Parent();
child.Parent = parent2;
context.SaveChanges();

It will change the parent but not audit the change. In order to audit the change of parent, the following code will work:

Parent parent2 = new Parent();
context.Parents.Add(parent2);
context.SaveChanges(); // first need to save the parent
child.Parent = parent2;
context.SaveChanges();

or if you know the new parent Id
or when its an existing parent

child.ParentId = 32;
context.SaveChanges();

System.Data.SqlClient.SqlException: Invalid column name 'TableName', while Creating log for saving\adding the entity.

public static int GetLastAuditLogId(ITrackerContext context, string tableName, object primaryKey)
{
string key = primaryKey.ToString();
return context.AuditLog.Where(x => x.TableName == tableName && x.RecordId == key).OrderByDescending(x => x.AuditLogId).Select(x => x.AuditLogId).FirstOrDefault();
return 0;
}

As the AuditLog modal does not contains tableName, hence its giving compilation error.

using TrackerEnabledDbContext.Identity; is not Found

So, I've just freshly installed TrackerEnabledDbContext, but I cannot integrate to my new ASP MVC 5 application. It says that I need to inherit from TrackerIdentityContext, but the assemblies only contain TrackerEnabledDbContext and TrackerEnabledDbContext.Models. Any solutions?

TrackerContext cannot be mocked with Moq framework

When trying to mock a type derived from TrackerContext with the Moq framework there is an issue which prevents the mock from being instantiated. The issue is described in this bug report for Moq:

castleproject/Core#106

Whilst it appears this is an issue with Moq, it can be worked around by ensuring that type names of generic types match between the interface and the class.

Tests Failing on CI

Build is failing for unknown reason on appveyor CI.

says : Invalid object name 'dbo.SoftDeletableModels'.

Failed   ShouldCreateSoftDeleteLog 
Error Message: 
   Test method TrackerEnabledDbContext.IntegrationTests.SoftDeleteTests.ShouldCreateSoftDeleteLog threw exception: 
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Invalid object name 'dbo.SoftDeletableModels'.
Stack Trace: 
    at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
   at System.Data.SqlClient.SqlDataReader.get_MetaData()
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
   at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
   at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
   at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
   at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
   at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
   at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
   at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
 --- End of inner exception stack trace ---
    at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
   at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
   at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
   at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
   at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
   at System.Data.Entity.Internal.InternalContext.SaveChanges()
 --- End of inner exception stack trace ---
    at System.Data.Entity.Internal.InternalContext.SaveChanges()
   at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   at System.Data.Entity.DbContext.SaveChanges()
   at TrackerEnabledDbContext.TrackerContext.SaveChanges(Object userName) in C:\projects\tracker-enabled-dbcontext\TrackerEnabledDbContext\TrackerContext.cs:line 52
   at TrackerEnabledDbContext.TrackerContext.SaveChanges() in C:\projects\tracker-enabled-dbcontext\TrackerEnabledDbContext\TrackerContext.cs:line 71
   at TrackerEnabledDbContext.IntegrationTests.SoftDeleteTests.ShouldCreateSoftDeleteLog() in C:\projects\tracker-enabled-dbcontext\TrackerEnabledDbContext.IntegrationTests\SoftDeleteTests.cs:line 32

Cant run unit tests from TrackerEnabledDbContext.Identity.IntegrationTests project

When tried to execute the

enable-migrations -ContextProjectName TrackerEnabledDbContext.Identity.IntegrationTests -StartUpProjectName TrackerEnabledDbContext.Identity.IntegrationTests -ContextTypeName TrackerEnabledDbContext.Identity.IntegrationTests.TestTrackerIdentityContext -ProjectName TrackerEnabledDbContext.Identity.IntegrationTests -verbose

the following error is generated

Using StartUp project 'TrackerEnabledDbContext.Identity.IntegrationTests'.
System.TypeLoadException: Method 'Set' in type 'TrackerEnabledDbContext.Identity.TrackerIdentityContext`1' from assembly 'TrackerEnabledDbContext.Identity, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4f92af0b908c4a0a' does not have an implementation.
   at System.Reflection.RuntimeAssembly.GetType(RuntimeAssembly assembly, String name, Boolean throwOnError, Boolean ignoreCase, ObjectHandleOnStack type)
   at System.Reflection.RuntimeAssembly.GetType(String name, Boolean throwOnError, Boolean ignoreCase)
   at System.Reflection.Assembly.GetType(String name)
   at System.Data.Entity.Utilities.TypeFinder.FindType(Type baseType, String typeName, Func`2 filter, Func`2 noType, Func`3 multipleTypes, Func`3 noTypeWithName, Func`3 multipleTypesWithName)
   at System.Data.Entity.Migrations.Design.ToolingFacade.GetContextTypeRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.GetContextType(String contextTypeName)
   at System.Data.Entity.Migrations.EnableMigrationsCommand.FindContextToEnable(String contextTypeName)
   at System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Method 'Set' in type 'TrackerEnabledDbContext.Identity.TrackerIdentityContext`1' from assembly 'TrackerEnabledDbContext.Identity, Version=1.0.0.0, Culture=neutral, PublicKeyToken=4f92af0b908c4a0a' does not have an implementation.

Hence the database needed to run tests can't be created.

The Build is broken due to a referenced/missing property "TableName" in AuditLog class..

Error CS1061 'AuditLog' does not contain a definition for 'TableName' and no extension method 'TableName' accepting a first argument of type 'AuditLog' could be found (are you missing a using directive or an assembly reference?) TrackerEnabledDbContext.Common C:\Code Library\tracker-enabled-dbcontext-master\TrackerEnabledDbContext.Common\CommonTracker.cs 121

Generally it's looking for a property called TableName that is not declared inside the type AuditLog.

Is this intended to work with 1:1-relations?

Hello.

I am evaluating this tracker and so far it works fine for simple objects. However if I have an object (principal) with a 1:1 relation, I only get audited changes for the principal object - if I change any property of the dependant object no change will show up. Not on creating, not on updating.

Both objects are saved in 1 step of db.SaveChanges().

Before I start to dig deeper and create a small sample for this special case I first wanted to confirm if those kinds of relations are even supported to be tracked.

Best regards,
Michael

Incorrect assembly versions

region Assembly TrackerEnabledDbContext.Identity.dll, v1.0.0.0

// ~TrackerEnabledDbContext.Identity.1.1.0\lib\net45\TrackerEnabledDbContext.Identity.dll

endregion

Simple HistoryTable

Hello, I found your nugget (sorry meant nuget :D ) , I am looking for a simple historytable for e.g. given a BookTable independent of the main table to track history BookHistoryTable where I can preform regular query operations.

I read the wiki, my questions are

  1. After I install EF, and your nuget, How can I configure EF to give me an autoHistoryTable
  2. Will I get an automatic model out of the DbContext Collection for the BookHistoryTable if I use your nuget
  3. Can I perform CRUD operations besides the DbAudits, or will this mess it up?
  4. How can I add custom columns, userId, Lat Long?
  5. Are there any limitations on performance, or can I use this as any regular table

Appreciate any insight, this is exactly what I was looking for. 👍

Empty AuditLog

when I call the SaveChanges(userid) method and my entity don't have any data changes, for example a user go the the edit option, and click on save without changing anything, the AuditLog get the operation information but the AuditLogDetails dont have any, of course, the user didn´t change anything, Its there a way to ignore this operations when no data was changed, i mean to ignore the audit on AuditLog table

SaveChanges logs all properties including no changes

Version 3.1.0 SaveChanges logs all properties including no changes with identical OldValue and NewValue values. Does it make sense? Here is my example:
await db.SaveChangesAsync(User.Identity.Name);
Before version 3.1.0 I used to use 2.7 and it worked correctly logging only changes.
Please update IsValueChanged void condition with
(StateOf(_dbEntry) == EntityState.Modified && prop.IsModified && prop.CurrentValue != prop.OriginalValue) ;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.