Generic Create or Update method for CRM 2016 Early bound entities

644 Views Asked by At

I've got this method I'm trying to create for CRM.

internal Guid CreateOrUpdateRecord(Entity entity)
{
    var guid = Guid.Empty;

    if (entity.Id == null || entity.Id == Guid.Empty)
    {
        guid = _serviceProxy.Create(entity);
    }
    else
    {
        _XRM.UpdateObject(entity);
        _XRM.SaveChanges();
        //_serviceProxy.Update(entity);

        guid = entity.Id;
    }

    return guid;
}

The purpose of it being that I dont need to care if an object is new or gotten from CRM so that my code can just set the variables and throw it in this method to save or update it. With this I don't need to create if structures in multiple places to deal with this issue every time.. I'm using this for multiple entity types.

The code is however giving me some grief in the update method.

This code

_XRM.UpdateObject(entity);
_XRM.SaveChanges()

has a tendency to throw:

The context is not currently tracking the 'xxx' entity.

and this

_serviceContext.Update(entity);

throws:

EntityState must be set to null, Created (for Create message) or Changed (for Update message) CRM C#

So, any suggestions as to how I should create a single method I can throw any Entity into and it will get updated or created accordingly.

Update changed the update portion of the method to:

{
    if(_XRM.IsAttached(entity) == false)
    {
        _XRM.Attach(entity);
    }

    _XRM.UpdateObject(entity);
    _XRM.SaveChanges();
    guid = entity.Id;
}

Not sure if this is the best way, but it seems to work.

1

There are 1 best solutions below

0
On

I believe just creating an entity does not add it, which is why you have to attach it. This method is a rather dangerous method in that it doesn't allow for Alternate Keys in update. In that case, the entity will not have an Id, but should have the appropriate attributes that define the alternate key used for the update.