ess/src/API/EMBC.ESS/Utilities/Dynamics/EssContext.cs
/// <summary>
/// Check if the entity is already tracked by the context, if no, then attach and return, if yes, return the tracked entity instead
/// </summary>
/// <typeparam name="TEntity">entity type</typeparam>
/// <param name="context">Dynamics context</param>
/// <param name="entitySetName">name of the entity set</param>
/// <param name="entity">the entity to attach</param>
/// <param name="entityKeyGetter"> a function to resolve the entity id</param>
/// <returns>a tracked entity - either existing or newly attached</returns>
Check if the entity is already tracked by the context, if no, then attach and return, if yes, return the tracked entity instead
Check if the entity is already tracked by the context if no then attach and return if yes return the tracked entity instead
public static TEntity AttachOrGetTracked<TEntity>(this EssContext context, string entitySetName, TEntity entity, Func<TEntity, Guid?> entityKeyGetter)
            where TEntity : crmbaseentity
        {
            var currentEntityKey = entityKeyGetter(entity);
            if (!currentEntityKey.HasValue) return entity;
            var matchedEntity = context.EntityTracker.Entities
                .Where(ed => ed.Entity is TEntity && entityKeyGetter((TEntity)ed.Entity) == currentEntityKey)
                .SingleOrDefault()?.Entity as TEntity;
            if (matchedEntity == null) context.AttachTo(entitySetName, entity);
            return matchedEntity ?? entity;
        }
public static TEntity AttachOrGetTracked < TEntity > ( this EssContext context , string entitySetName , TEntity entity , Func < TEntity , Guid ? > entityKeyGetter ) where TEntity : crmbaseentity { var currentEntityKey = entityKeyGetter ( entity ) ; if ( ! currentEntityKey . HasValue ) return entity ; var matchedEntity = context . EntityTracker . Entities . Where ( ed => ed . Entity is TEntity && entityKeyGetter ( ( TEntity ) ed . Entity ) == currentEntityKey ) . SingleOrDefault ( ) ? . Entity as TEntity ; if ( matchedEntity == null ) context . AttachTo ( entitySetName , entity ) ; return matchedEntity ?? entity ; }
Check if the entity is already tracked by the context, if no, then attach and return, if yes, return the tracked entity instead
Check if the entity is already tracked by the context if no then attach and return if yes return the tracked entity instead
a tracked entity - either existing or newly attached
a tracked entity - either existing or newly attached
EssContext
this
entitySetName
string
name of the entity set
name of the entity set
entity
TEntity
the entity to attach
the entity to attach
entityKeyGetter
Func<TEntity, Guid?>
a function to resolve the entity id
a function to resolve the entity id
context
None
typeparam
None