EntityFramework-Plus icon indicating copy to clipboard operation
EntityFramework-Plus copied to clipboard

Audit: Destination array was not long enough. Check the destination index, length, and the array's lower bounds. Parameter name: destinationArray

Open suspy69 opened this issue 7 years ago • 4 comments

Hello. I'm getting the destination array error randomly. When it happens if I try and make the call again if works fine. Any thoughts ?

The stacktrace reads: at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable) at System.Collections.Generic.List1.CopyTo(T[] array, Int32 arrayIndex) at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at Z.EntityFramework.Plus.AuditConfiguration.Clone() at Z.EntityFramework.Plus.Audit.<>c.<.ctor>b__1_0() at System.Lazy1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) at System.Lazy1.CreateValue() at EF.Data.CommonContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken) at API.Controllers.EmailsController.GetImmediateEmailJob(Guid jobId)

The code is .net core 2.2 and hosted on azure.

suspy69 avatar Dec 07 '18 13:12 suspy69

Hello @suspy69 ,

It's possible to project a project sample with this issue?

The Clone method is pretty straightforward. I guess the issue happen somewhere when we create a new List here: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/src/shared/Z.EF.Plus.Audit.Shared/AuditConfiguration.cs#L146-L174 but I don't think we will be able to find how to reproduce it with the information you provided.

Best Regards,

Jonathan


Performance Libraries context.BulkInsert(list, options => options.BatchSize = 1000); Entity Framework Extensions • Entity Framework Classic • Bulk Operations • Dapper Plus

Runtime Evaluation Eval.Execute("x + y", new {x = 1, y = 2}); // return 3 C# Eval Function • SQL Eval Function

JonathanMagnan avatar Dec 07 '18 13:12 JonathanMagnan

Sorry about that. So, my context is setup like this:

public CommonContext(DbContextOptions<CommonContext> options) : base(options)
        {
            AuditManager.DefaultConfiguration.SoftDeleted<BaseModels>(x => x.IsDeleted);
            AuditManager.DefaultConfiguration.AutoSavePreAction = (context, audit) =>
            (context as CommonContext).AuditEntries.AddRange(audit.Entries);
            //AuditManager.DefaultConfiguration.IgnorePropertyUnchanged = true;
            this.Database.SetCommandTimeout(120);
        }

        static CommonContext()
        {
            AuditManager.DefaultConfiguration.SoftDeleted<BaseModels>(x => x.IsDeleted);
            AuditManager.DefaultConfiguration.AutoSavePreAction = (context, audit) =>
            (context as CommonContext).AuditEntries.AddRange(audit.Entries);
            //AuditManager.DefaultConfiguration.IgnorePropertyUnchanged = true;
        }

And my SaveChangesAsync override like this:

public override async Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken())
        {
            var selectedEntityList = ChangeTracker.Entries()
                                    .Where(x => x.Entity is BaseModels &&
                                    (x.State == EntityState.Added || x.State == EntityState.Modified));
            var entityList = selectedEntityList.ToList();

            Guid userID = Guid.Empty;
            foreach (var entity in entityList)
            {
                if (((BaseModels)entity.Entity).ModifiedBy.HasValue)
                {
                    userID = ((BaseModels)entity.Entity).ModifiedBy.Value;
                    break;
                }
                else
                {
                    userID = ((BaseModels)entity.Entity).CreatedBy;
                    break;
                }
            }

            var audit = new Audit();
            if (userID != Guid.Empty)
                audit.CreatedBy = userID.ToString();

            audit.PreSaveChanges(this);
            var rowsAffected = await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken).ConfigureAwait(false);
            audit.PostSaveChanges();

            Guid transactionID = Guid.NewGuid();
            Guid uniqueId = Guid.NewGuid();
            foreach (AuditEntry entry in audit.Entries)
            {
                if (entry.EntityTypeName == "Application" || entry.EntityTypeName == "Job")
                {
                    AuditEntryProperty entityId = entry.Properties.Where(r => r.PropertyName == "ID").FirstOrDefault();
                    if (entityId != null)
                    {
                        if (!string.IsNullOrWhiteSpace(entityId.NewValueFormatted))
                            transactionID = Guid.Parse(entityId.NewValueFormatted);
                        else if (!string.IsNullOrWhiteSpace(entityId.OldValueFormatted))
                            transactionID = Guid.Parse(entityId.OldValueFormatted);
                    }
                }
            }

            foreach (AuditEntry entry in audit.Entries)
            {
                entry.EntitySetName = string.Format("{0}_{1}", transactionID, uniqueId);
                if (userID != Guid.Empty)
                    entry.CreatedBy = userID.ToString();
            }

            if (audit.Configuration.AutoSavePreAction != null)
            {
                audit.Configuration.AutoSavePreAction(this, audit);
                await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken).ConfigureAwait(false);
            }

            //this.AuditEntries.AddRange(audit.Entries);
            //await base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken).ConfigureAwait(false);

            return rowsAffected;
        }

The only change that I made to the model is to update a date field. Again the error occurs randomly.

suspy69 avatar Dec 07 '18 13:12 suspy69

Hello @suspy69 ,

Could you remove this part of code from your constructors

public CommonContext(DbContextOptions<CommonContext> options) : base(options)
{
	AuditManager.DefaultConfiguration.SoftDeleted<BaseModels>(x => x.IsDeleted);
	AuditManager.DefaultConfiguration.AutoSavePreAction = (context, audit) =>
	(context as CommonContext).AuditEntries.AddRange(audit.Entries);
	//AuditManager.DefaultConfiguration.IgnorePropertyUnchanged = true;
}

Those are global configuration, so every time you create a new context, you override default configuration which might lead to some side effect like this one.

That's an issue we solved with EF Classic: https://entityframework-classic.net/, we do not longer have global configuration since too many people made the same "mistake".

All configuration should be in your static constructor which it looks you already have.

Best Regards,

Jonathan

JonathanMagnan avatar Dec 07 '18 16:12 JonathanMagnan

Thank you Jonathan.

I'll try that and I'll let you know.

suspy69 avatar Dec 07 '18 16:12 suspy69