How to prevent duplicating entities during entity updates?

36 Views Asked by At

I'm developing a .NET-based web server and encountering a issue. There's a one-to-one relationship between two entities, referred to as D and P. I'm currently working on implementing a PUT endpoint to update entity D. To accomplish this, I pass an instance of D, along with the corresponding instance of P, to the following method:

    public virtual async Task<TEntity> Update(TEntity entityToUpdate)
    {
        if (entityToUpdate == null)
        {
            throw new BadRequestException(GenericErrors.NULL_ARGUMENT, new string[] { typeof(TEntity).ToString() });
        }

        var entry = context.Entry(entityToUpdate);

        entityToUpdate.DateUpdated = DateTime.Now;
        if (entry.State == EntityState.Detached)
        {
            var set = context.Set<TEntity>();

            TEntity attachedEntity = await set.FindAsync(entityToUpdate.Id);  // You need to have access to key

            //Set Previous DateCreated
            entityToUpdate.DateCreated = attachedEntity.DateCreated;

            if (attachedEntity != null)
            {
                var attachedEntry = context.Entry(attachedEntity);
                attachedEntry.CurrentValues.SetValues(entityToUpdate);
            }
            else
            {
                entry.State = EntityState.Modified; // This should attach entity
            }
        }

        return entityToUpdate;
    }

But each time a new instance of P is added (even if the instance of D references a pre-existing instance of P). How can I solve this issue? I'm new with .NET :)

0

There are 0 best solutions below