Coder Social home page Coder Social logo

nhibernate-envers's People

Contributors

crazyraisy avatar dennis-gr avatar fabiomaulo avatar jpenniman avatar jrauber avatar nikitaegorov avatar owerkop avatar patearl avatar patrykpiotrmarek avatar peteappleton avatar rogerkratz avatar t-castelan avatar wojtek-abakus avatar

Stargazers

 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

nhibernate-envers's Issues

Flushing audit data during BeforeTransactionCompletion is forbidden in some cases since NH 5

According to nhibernate-reference

As of NHibernate v5.0, using transaction scope and trying to use the session connection within AfterTransactionCompletion is forbidden and will raise an exception. If the setting transaction.use_connection_on_system_prepare is false, it will forbid any connection usage from BeforeTransactionCompletion event too, when this event is triggered by a transaction scope commit or rollback.

But, as we can see here AuditProcessManager.cs, only one way to flush audit data is inside BeforeTransactionCompletion.
Now it leads to throwing NHibernate.HibernateException Connection usage is currently disallowed

So, it looks like, we have to serve opportunity of flushing audit data on NH session flush.

Envers in Db2 invalid cast

Hello,
we are having quite old instance of Nhibernate in our company.
We are setting it up by block:

protected static readonly Action<HibConfiguration> EnversBaseExtension = x =>
        {
            x.SetEnversProperty(ConfigurationKey.RevisionFieldName, "REV_ID");
            x.SetEnversProperty(ConfigurationKey.AuditTableSuffix, "_H");
            x.SetEnversProperty(ConfigurationKey.StoreDataAtDelete, true);
            x.IntegrateWithEnvers(new AttributeConfiguration());
        };

All seems fine for Oracle and MsSql, however we recently added Db2 to one of our supported Databases, but we face error deep in the Nhibernate sources.
I assume it is caused by implementation class RevisionTypeType: IUserType.

Is it somehow possible to override this? In our company we still use version 2.0.0.500.

Exception thrown: 'System.InvalidCastException' in mscorlib.dll
Additional information: Invalid cast from 'NHibernate.Envers.RevisionType' to 'System.Byte[]'. occurred

sample table is defined this way:

CREATE TABLE SOMETABLE_H (
                REC_ID INT NOT NULL, 
                ...Whatever...,
                REV_ID INT NOT NULL, 
                REVTYPE INT NOT NULL,
                PRIMARY KEY (REC_ID, REV_ID))

We expect, that this enum 'NHibernate.Envers.RevisionType' would be mapped to INT without any trouble without using IUserType for conversion.

Classmap Table Name

I have class that I am mapping using FluentNHibernate.Mapping.ClassMap with the table defined as follows:
Table("[Product]");

I was getting a SQL error:
SqlException: Incorrect syntax near '_AUD'.

I logged the SQL produced by Nhibernate to a file and figured out that Nhibernate.Envers was trying to store my audit data to table [Product]_AUD instead of Product_AUD, I fixed the issue for myself by removing the brackets:

Table("Product");

Running into problem with table per class mapping with multiple subclasses

We have been looking at using Envers, but have run into a road block. We use a table/class structure that is using table per class inheritance for a couple of classes. While NHibernate and Envers are loading, an error occurs when it tries to create the tables for the subclasses.

NHibernate.MappingException : Unable to build the insert statement for class NHibernate.Envers.Tests.Integration.Inheritance.TablePerClass.Discriminate.ParentEntity: a failure occured when adding the discriminator
----> System.ArgumentException : The column 'TypeId' has already been added in this SQL builder
Parameter name: columnName

I wasn't able to figure out the problem, so I created a unit test based off of the DiscriminateFormula unit test, but with the discriminate set using a value in the mapping and I also added an additional sub type "OtherChildEntity" that extends ParentEntity like ChildEntity does. I also added mappings, initial data loading and tests for the OtherChildEntity.

The test case also results in the same error being thrown during initialization. I have attached a zip file with the test code.

NHibernate.Envers.Tests.Integration.Inheritance.TablePerClass.Discriminate.DiscriminatorTest
Discriminate.zip

Please let me know if there is anything I can do to assist.

Extend modified flags to support track changes within components

One question, I have mapped the fields this way:

Component(x => x.RentSearchParameters, m => { m.Map(x => x.MinPrice).Column("precio_min_alquiler").Nullable(); m.Map(x => x.MaxPrice).Column("precio_max_alquiler").Nullable(); m.Map(x => x.ApproxPosition).Column("posicion_aproximada_alquiler").Nullable(); m.Map(x => x.Timing).Column("timing_alquiler").Nullable(); m.Map(x => x.Step).Column("step_alquiler").Nullable(); });

Is it possible to audit them separately?

precio_min_alquiler - MinPrice_mod
precio_max_alquiler - MaxPrice_mod
posicion_aproximada_alquiler - ApproxPosition_mod
...

instead of

precio_min_alquiler
precio_max_alquiler
posicion_aproximada_alquiler
RentSearchParameters_mod
...

Build Warning with new NHibernate 5.3 package

It seems the latest NHibernate version 5.3 package leads to a build warning:

warning NU1608: Detected package version outside of dependency constraint: NHibernate.Envers 5.2.3 requires NHibernate (>= 5.2.1 && < 5.3.0) but version NHibernate 5.3.0 was resolved.

Unexpected session flush when calling AuditReader.GetCurrentRevision

Hello

There is a problem when calling AuditReader().GetCurrentRevision(true) - it leads to immediate flush of uncommited session data. If calling GetCurrentRevision with persist = false, then problem is gone. It seems, that unexpected flush happens when saving revisionData by DefaultRevisionInfoGenerator.

I made a PR to illustrate the problem: #21

GetCurrentTransaction is null

I have an issue with the latest version with NHibernate
If I have a flush without a transaction I have this error

System.ArgumentNullException: 'Value cannot be null.
Parameter name: key'

I debugged the code and the issue is here
It always returns null if we are flushing.

var transaction = (object)session.GetCurrentTransaction() ?? System.Transactions.Transaction.Current;

this change

This worked before that change:

transaction = session.Transaction;

Error retrieving Geography column with msql server

NHibernate.ADOException: There was a problem converting an DbDataReader to NDataReader
---> System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.SqlServer.Types, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'. El sistema no puede encontrar el archivo especificado.
File name: 'Microsoft.SqlServer.Types, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'
at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, RuntimeAssembly assemblyContext, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, StackCrawlMark& stackMark, AssemblyLoadContext assemblyLoadContext)
at System.Reflection.Assembly.Load(AssemblyName assemblyRef)
at System.Data.SqlClient.SqlConnection.ResolveTypeAssembly(AssemblyName asmRef, Boolean throwOnError)
at System.TypeNameParser.ResolveAssembly(String asmName, Func2 assemblyResolver, Boolean throwOnError, StackCrawlMark& stackMark) at System.TypeNameParser.ConstructType(Func2 assemblyResolver, Func4 typeResolver, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark) at System.TypeNameParser.GetType(String typeName, Func2 assemblyResolver, Func4 typeResolver, Boolean throwOnError, Boolean ignoreCase, StackCrawlMark& stackMark) at System.Type.GetType(String typeName, Func2 assemblyResolver, Func`4 typeResolver, Boolean throwOnError)
at System.Data.SqlClient.SqlConnection.CheckGetExtendedUDTInfo(SqlMetaDataPriv metaData, Boolean fThrow)
at System.Data.SqlClient.SqlDataReader.GetValueFromSqlBufferInternal(SqlBuffer data, _SqlMetaData metaData)
at System.Data.SqlClient.SqlDataReader.GetValues(Object[] values)
at NHibernate.Driver.NDataReader.NResult.Create(DbDataReader reader, Boolean isMidstream)
at NHibernate.Driver.NDataReader.Create(DbDataReader reader, Boolean isMidstream)

--- End of inner exception stack trace ---
at NHibernate.Driver.NDataReader.Create(DbDataReader reader, Boolean isMidstream)
at NHibernate.Driver.NHybridDataReader.ReadIntoMemory()
at NHibernate.AdoNet.AbstractBatcher.CheckReaders()
at NHibernate.AdoNet.AbstractBatcher.ExecuteReader(DbCommand cmd)
at NHibernate.Loader.Loader.GetResultSet(DbCommand st, QueryParameters queryParameters, ISessionImplementor session, IResultTransformer forcedResultTransformer)
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies, IResultTransformer forcedResultTransformer, QueryCacheResultBuilder queryCacheResultBuilder)
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies, IResultTransformer forcedResultTransformer, QueryCacheResultBuilder queryCacheResultBuilder)
at NHibernate.Loader.Loader.LoadEntity(ISessionImplementor session, Object id, IType identifierType, Object optionalObject, String optionalEntityName, Object optionalIdentifier, IEntityPersister persister)
at NHibernate.Loader.Entity.AbstractEntityLoader.Load(ISessionImplementor session, Object id, Object optionalObject, Object optionalId)
at NHibernate.Loader.Entity.AbstractEntityLoader.Load(Object id, Object optionalObject, ISessionImplementor session)
at NHibernate.Persister.Entity.AbstractEntityPersister.Load(Object id, Object optionalObject, LockMode lockMode, ISessionImplementor session)
at NHibernate.Event.Default.DefaultLoadEventListener.LoadFromDatasource(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.DoLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.Load(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options)
at NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType)
at NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType)
at NHibernate.Impl.SessionImpl.ImmediateLoad(String entityName, Object id)
at NHibernate.Proxy.AbstractLazyInitializer.Initialize()
at NHibernate.Proxy.AbstractLazyInitializer.GetImplementation()
at AppRevisionEntityProxy.GetHashCode()
at NHibernate.Type.ComponentType.GetHashCode(Object x)
at NHibernate.Type.ComponentType.GetHashCode(Object x, ISessionFactoryImplementor factory)
at NHibernate.Engine.EntityKey.GenerateHashCode(IEntityPersister persister, Object id)
at NHibernate.Engine.EntityKey..ctor(Object id, IEntityPersister persister)
at NHibernate.Impl.AbstractSessionImpl.GenerateEntityKey(Object id, IEntityPersister persister)
at NHibernate.Loader.Loader.GetRowFromResultSet(DbDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies, IResultTransformer forcedResultTransformer, QueryCacheResultBuilder queryCacheResultBuilder, Action2 cacheBatchingHandler) at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies, IResultTransformer forcedResultTransformer, QueryCacheResultBuilder queryCacheResultBuilder) at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies, IResultTransformer forcedResultTransformer, QueryCacheResultBuilder queryCacheResultBuilder) at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters, IResultTransformer forcedResultTransformer, QueryCacheResultBuilder queryCacheResultBuilder) at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) at NHibernate.Loader.Loader.List(ISessionImplementor session, QueryParameters queryParameters, ISet1 querySpaces)
at NHibernate.Loader.Hql.QueryLoader.List(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Hql.Ast.ANTLR.QueryTranslatorImpl.List(ISessionImplementor session, QueryParameters queryParameters)
at NHibernate.Engine.Query.HQLQueryPlan.PerformList(QueryParameters queryParameters, ISessionImplementor session, IList results)
at NHibernate.Impl.SessionImpl.List(IQueryExpression queryExpression, QueryParameters queryParameters, IList results, Object filterConnection)
at NHibernate.Impl.SessionImpl.List(IQueryExpression queryExpression, QueryParameters queryParameters, IList results)
at NHibernate.Impl.AbstractSessionImpl.List[T](IQueryExpression query, QueryParameters parameters)
at NHibernate.Impl.AbstractQueryImpl2.ListT
at NHibernate.Envers.Query.Impl.AbstractRevisionsQuery1.BuildAndExecuteQuery[TResult]() at NHibernate.Envers.Query.Impl.HistoryQuery2.Results()
at Guru.Repository.Revision.RevisionRepository.Paginated[T,K](IAuditQuery count, IEntityAuditQuery1 query, PageRequest pageRequest) in C:\Users\Roberto\source\repos\BrainsRE\Guru.Repository\Revision\RevisionRepository.cs:line 74 at _dynamic_Guru.Repository.Revision.RevisionRepository.Paginated(Object , Object[] ) at Spring.Aop.Framework.DynamicMethodInvocation.InvokeJoinpoint() at Spring.Transaction.Interceptor.TransactionInterceptor.Invoke(IMethodInvocation invocation) at CompositionAopProxy_601bc1ef64ed4e6899fb7b855686172d.Paginated[T,K](IAuditQuery count, IEntityAuditQuery1 query, PageRequest pageRequest)
at Guru.Service.Master.DesktopService.PaginatedHistory(DesktopRevisionFindFilter filter, PageRequest pageRequest)
at _dynamic_Guru.Service.Master.DesktopService.PaginatedHistory(Object , Object[] )
at Spring.Aop.Framework.DynamicMethodInvocation.InvokeJoinpoint()
at Spring.Transaction.Interceptor.TransactionInterceptor.Invoke(IMethodInvocation invocation)
at CompositionAopProxy_d1f6f7a263474471a1fb220918d98afa.PaginatedHistory(DesktopRevisionFindFilter filter, PageRequest pageRequest)
at Guru.Proxy.Master.DesktopProxy.PaginatedHistory(DesktopRevisionFindRequest request)
at Guru.Controllers.Master.DesktopController.History(DesktopRevisionFindRequest request)
at lambda_method(Closure , Object , Object[] )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ExceptionContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

NHibernate.MappingException: No persister for: ProxyForFieldInterceptor

After add envers to my project. I've got exception

NHibernate.MappingException: No persister for: CantonProxyForFieldInterceptor
   at NHibernate.Impl.SessionFactoryImpl.GetEntityPersister(String entityName)
   at NHibernate.Impl.SessionImpl.GetEntityPersister(String entityName, Object obj)
   at NHibernate.Envers.Tools.Toolz.getIdentifier(ISessionImplementor session, Object obj)
   at NHibernate.Envers.Tools.Toolz.EntitiesEqual(ISessionImplementor session, Object obj1, Object obj2)
   at NHibernate.Envers.Entities.Mapper.Relation.ToOneIdMapper.MapToMapFromEntity(ISessionImplementor session, IDictionary`2 data, Object newObj, Object oldObj)
   at NHibernate.Envers.Entities.Mapper.MultiPropertyMapper.Map(ISessionImplementor session, IDictionary`2 data, String[] propertyNames, Object[] newState, Object[] oldState)
   at NHibernate.Envers.Synchronization.Work.AddWorkUnit..ctor(ISessionImplementor sessionImplementor, String entityName, AuditConfiguration verCfg, Object id, IEntityPersister entityPersister, Object[] state)
   at NHibernate.Envers.Event.AuditEventListener.OnPostInsert(PostInsertEvent evt)
   at NHibernate.Action.EntityInsertAction.PostInsert()
   at NHibernate.Action.EntityInsertAction.Execute()
   at NHibernate.Engine.ActionQueue.InnerExecute(IExecutable executable)
   at NHibernate.Engine.ActionQueue.ExecuteActions[T](List`1 list)
   at NHibernate.Engine.ActionQueue.ExecuteActions()
   at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session)
   at NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event)
   at NHibernate.Impl.SessionImpl.Flush()
 <PackageReference Include="NHibernate" Version="5.3.9" />
 <PackageReference Include="NHibernate.Envers" Version="5.3.1" />

SchemaUpdate generate duplicate of foreign key

    alter table City_AUD
        add constraint FK6D86CDE09192A98F
        foreign key (REV)
        references REVINFO
  alter table City_AUD
        add constraint FKDB74ADA27CBE804D
        foreign key (REV)
        references REVINFO

Last version of Envers and NHib

Get audit history by ComponentAsId

Earlier I had white about bug #12

How can I get audit history using one of ComponentAsId member as filter?

Now I try to get history like this
var history = Session.Auditer().CreateQuery()
.ForRevisionsOfEntity(typeof(SomeEntUDF), false, true)
.Add(AuditEntity.Property("Id.Key1.Id").Eq(ent1.Id))
.GetResultList();

Assert.AreEqual(1, history.Count);

and I have an error
NHibernate.QueryException : could not resolve property: Id_Key1_Id of: NHibernate.Envers.Tests.NetSpecific.Integration.ComponentAsId.SomeEntUDF_AUD [select e__, r__ from NHibernate.Envers.Tests.NetSpecific.Integration.ComponentAsId.SomeEntUDF_AUD e__, NHibernate.Envers.DefaultRevisionEntity r__ where e__.Id_Key1_Id = :p0 and e_.originalId.REV.id = r__.id order by e__.originalId.REV.id asc]

Do I do something wrong or it's a new bug?

Incorrect audit table insert on tables with tree structure

Hello.

I have a problem with envers when an audited table has a tree structure.
When I insert a row without any parent it inserts correctly to an audit table with revision type 0 (Added).
Then I try to insert a child row with an ID pointing to parent row (by creating an empty entity with only ID set, it works normallny with nHibernate).

The result is that Envers tries to insert an audit table row with with revision type 1 (Modified) that corresponds to the parent row with all the fields set to null...
It's very strange, but when I comment out the HasMany mapping it works ok.

I have made a sample project to show that behavior, it crashes because one of the fields is set to be not null.

EnversTest.zip

Can't write CLR type NHibernate.Envers.RevisionType exception after upgrading to Npgsql >= 4.0.0

Hello.

Recently we've upgraded our PostgreSQL database driver to version 4.0.2 and Evners started to throw exceptions. It was working fine on 3.x.x branch of the driver.
From exception stacks I can tell that there's some wrong revtype mapping (probably enum is passed instead of enum casted to short).

Stack is:

An exception of type 'NHibernate.AssertionFailure' occurred in NHibernate.dll but was not handled in user code
Additional information: Unable to perform BeforeTransactionCompletion callback
 
   w NHibernate.Engine.ActionQueue.BeforeTransactionCompletionProcessQueue.BeforeTransactionCompletion()
   w NHibernate.Impl.SessionImpl.BeforeTransactionCompletion(ITransaction tx)
   w NHibernate.Transaction.AdoTransaction.Commit()

And the inner exception:

Can't write CLR type NHibernate.Envers.RevisionType with handler type Int16Handler

   w lambda_method(Closure , NpgsqlTypeHandler , Object , NpgsqlLengthCache& , NpgsqlParameter )
   w Npgsql.TypeHandling.NpgsqlSimpleTypeHandler`1.ValidateObjectAndGetLength(Object value, NpgsqlLengthCache& lengthCache, NpgsqlParameter parameter)
   w Npgsql.NpgsqlParameter.ValidateAndGetLength()
   w Npgsql.NpgsqlCommand.ValidateParameters()
   w Npgsql.NpgsqlCommand.<ExecuteDbDataReader>d__100.MoveNext()
--- Koniec śladu stosu z poprzedniej lokalizacji, w której wystąpił wyjątek ---
   w System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   w System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   w Npgsql.NpgsqlCommand.<ExecuteNonQuery>d__92.MoveNext()
--- Koniec śladu stosu z poprzedniej lokalizacji, w której wystąpił wyjątek ---
   w System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   w System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   w Npgsql.NpgsqlCommand.ExecuteNonQuery()
   w NHibernate.AdoNet.AbstractBatcher.ExecuteNonQuery(DbCommand cmd)
   w NHibernate.AdoNet.NonBatchingBatcher.AddToBatch(IExpectation expectation)
   w NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Boolean[] notNull, Int32 j, SqlCommandInfo sql, Object obj, ISessionImplementor session)
   w NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object id, Object[] fields, Object obj, ISessionImplementor session)
   w NHibernate.Action.EntityInsertAction.Execute()
   w NHibernate.Engine.ActionQueue.InnerExecute(IExecutable executable)
   w NHibernate.Engine.ActionQueue.ExecuteActions(IList list)
   w NHibernate.Engine.ActionQueue.ExecuteActions()
   w NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutions(IEventSource session)
   w NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event)
   w NHibernate.Impl.SessionImpl.Flush()
   w NHibernate.Envers.Synchronization.AuditProcess.DoBeforeTransactionCompletion() w D:\stuff\code\envers\Src\NHibernate.Envers\Synchronization\AuditProcess.cs:wiersz 166
   w NHibernate.Envers.Synchronization.AuditProcessManager.<>c__DisplayClass3_0.<Get>b__0() w D:\stuff\code\envers\Src\NHibernate.Envers\Synchronization\AuditProcessManager.cs:wiersz 35
   w NHibernate.Engine.ActionQueue.BeforeTransactionCompletionProcessQueue.BeforeTransactionCompletion()

NullReferenceException on AuditEventListener

I'm getting an exception using NHibernate Envers and ASP.NET Core 2.0

Diarias.WebApi.Infra.Middleware.ExceptionMiddleware:Error: System.NullReferenceException: Object reference not set to an instance of an object.
	at NHibernate.Envers.Event.AuditEventListener.OnPostInsert(PostInsertEvent evt) in D:\stuff\code\envers\Src\NHibernate.Envers\Event\AuditEventListener.cs:line 115
	at NHibernate.Action.EntityIdentityInsertAction.PostInsert()
	at NHibernate.Action.EntityIdentityInsertAction.Execute()
	at NHibernate.Engine.ActionQueue.InnerExecute(IExecutable executable)
	at NHibernate.Engine.ActionQueue.Execute(IExecutable executable)
	at NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object entity, EntityKey key, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
	at NHibernate.Event.Default.AbstractSaveEventListener.PerformSave(Object entity, Object id, IEntityPersister persister, Boolean useIdentityColumn, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
	at NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object entity, String entityName, Object anything, IEventSource source, Boolean requiresImmediateIdAccess)
	at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.SaveWithGeneratedOrRequestedId(SaveOrUpdateEvent event)
	at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.EntityIsTransient(SaveOrUpdateEvent event)
	at NHibernate.Event.Default.DefaultSaveOrUpdateEventListener.OnSaveOrUpdate(SaveOrUpdateEvent event)
	at NHibernate.Impl.SessionImpl.FireSaveOrUpdate(SaveOrUpdateEvent event)
	at NHibernate.Impl.SessionImpl.SaveOrUpdate(String entityName, Object obj)

Configuring my NHibernate

private void BuildAuditConfiguration()
        {

            //Configura o prefixo da tabela a ser utilizada como histórico de auditoria
            ConfigurationKey.AuditTablePrefix.SetUserValue(Configuration, "AUD_");

            //Configura o sufixo da tabela a ser utilizada como histórico de auditoria
            ConfigurationKey.AuditTableSuffix.SetUserValue(Configuration, "");

            //configura o schema onde as tabelas de auditoria estão/deverão ser criadas
            ConfigurationKey.DefaultSchema.SetUserValue(Configuration, "audit");

            //grava a última versão de um registro numa tabela auditada em caso de exclusão
            ConfigurationKey.StoreDataAtDelete.SetUserValue(Configuration, true);

            var enversConfig = new AttributeConfiguration();
            var eventListener = new AuditEventListener();

            Configuration.IntegrateWithEnvers(eventListener, enversConfig);
        }

NullReferenceException when many-to-many relation with the same key name as backreference

Hello.

There is a problem with Envers when you have a many-to-many relation between two entities and one of them has another many-to-one relation with the same key name. This works just fine in nHibernate, but when you enable Envers it crashes in NHibernate.Envers.Synchronization.Work.FakeBidirectionalRelationWorkUnit.FakeRelationChange.GenerateData method.

Missing Docs

I couldn't find any docs related to this library ? Old links do not work. Can you add docs link in readme?

True async suppport

AuditProcessManager and possibly other classes are lacking true async support. Database IO operations are blocking thread pool threads because AuditProcessManager's async methods just call the sync ones.

In this example, as entities are persisted and flushed by NHibernate with ISession.FlushAsync(), Envers calls ISession.Flush() on the audit entities:

...
00007F084F1005D0 00007F09A6EBCBA7 NHibernate.Impl.SessionImpl.Flush()
00007F084F100630 00007F09A6EAADF9 NHibernate.Envers.Synchronization.AuditProcessManager+transactionCompletionProcess.ExecuteBeforeTransactionCompletion()
00007F084F100650 00007F09A6EAACFD NHibernate.Envers.Synchronization.AuditProcessManager+transactionCompletionProcess.ExecuteBeforeTransactionCompletionAsync(System.Threading.CancellationToken)
00007F084F100660 00007F09A6EA9B52 NHibernate.Engine.ActionQueue+BeforeTransactionCompletionProcessQueue+<BeforeTransactionCompletionAsync>d__0.MoveNext()
00007F084F1006E0 00007F09A6EA9207 System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start[[NHibernate.Engine.ActionQueue+BeforeTransactionCompletionProcessQueue+<BeforeTransactionCompletionAsync>d__0, NHibernate]](<BeforeTransactionCompletionAsync>d__0 ByRef) [/_/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncMethodBuilderCore.cs @ 38]
00007F084F100720 00007F09A6EA9172 NHibernate.Engine.ActionQueue+BeforeTransactionCompletionProcessQueue.BeforeTransactionCompletionAsync(System.Threading.CancellationToken)
00007F084F100770 00007F09A6DFE4EC NHibernate.Impl.SessionImpl+<BeforeTransactionCompletionAsync>d__79.MoveNext()
00007F084F100830 00007F099FEC10AB System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) [/_/src/libraries/System.Private.CoreLib/src/System/Threading/ExecutionContext.cs @ 183]
00007F084F100890 00007F09A6EA8F89 System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[[System.Threading.Tasks.VoidTaskResult, System.Private.CoreLib],[NHibernate.Impl.SessionImpl+<BeforeTransactionCompletionAsync>d__79, NHibernate]].MoveNext(System.Threading.Thread) [/_/src/libraries/System.Private.CoreLib/src/System/Runtime/CompilerServices/AsyncTaskMethodBuilderT.cs @ 324]
00007F084F1008E0 00007F099FF9F396 System.Threading.Tasks.AwaitTaskContinuation.RunOrScheduleAction(System.Runtime.CompilerServices.IAsyncStateMachineBox, Boolean) [/_/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/TaskContinuation.cs @ 795]
00007F084F100920 00007F099FEE19B8 System.Threading.Tasks.Task.RunContinuations(System.Object) [/_/src/libraries/System.Private.CoreLib/src/System/Threading/Tasks/Task.cs @ 3374]
00007F084F1009D0 00007F09A6DFFC31 NHibernate.Impl.SessionImpl+<FlushAsync>d__65.MoveNext()
...

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.