urfnet / URF.Core

Unit of Work & Repositories Framework - .NET Core, NET Standard, Entity Framework Core. 100% extensible & lightweight.
https://github.com/urfnet
MIT License
309 stars 62 forks source link

Support for Detach Tracking State #51

Closed youngaj closed 5 years ago

youngaj commented 5 years ago

Is there a way to create a Detached TrackingState?

I'm running into a problem where I want to detach a graph of objects but the service/repo seems to only detach the top level entity. When I go to save the entity it complains that another entity with the same id already exists but it should be part of the detached object graph.

My reason for doing this (and perhaps there is a better way, which I'm very open to) is that I want to track/record the changes to certain fields of my entity into another table (ChangeHistory). In order to do that in my API controller I do the following.

                var original = _bulletService.GetById(dto.Id);
                _bulletService.Detach(original);
                if (original == null)
                    return NotFound();

                var bullet = EntityFactory.Parse(original, dto);
                _bulletService.ApplyChanges(bullet);
                _bulletService.Update(bullet);
                await _unitOfWork.SaveChangesAsync();
                _bulletService.AcceptChanges(bullet);

                //-- Save changes to Bullet
                var transactionId = Guid.NewGuid();
                var timeStamp = DateTime.Now;
                var changes = _bulletService.GetChanges(transactionId, timeStamp, original.CompositeKey, _currentUser, original, bullet);
                if (ListUtils.IsNonEmptyList(changes))
                {
                    changes.ForEach(x => _changeRecordService.Insert(x));
                    await _unitOfWork.SaveChangesAsync();
                }

The Parse function creates a copy of the original with the dto information overlain but does not overwrite the original to be used later as in a comparison.

If I could mark each entity in original as not tracked or Detached then I could avoid the error.

lelong37 commented 5 years ago

@tonysneed is there anything he do here with Trackable?

tonysneed commented 5 years ago

Detaching entities is an EF Core feature, and the default behavior is non-recursive, meaning they are detached one at a time. If you want to detach all the entities that are being tracked by EF, you will need to do this yourself from within your service. See this SO answer for an example.

tonysneed commented 5 years ago

Closing for now. Please re-open if needed.