public void AssignAttribute <TEntityProperty, TEntity>(Expression <Func <TEntity, TEntityProperty> > entityProperty, ITracingService tracingService = default(ITracingService)) where TEntity : EntityBase where TEntityProperty : EntityBase { var entity = this; entityProperty.PropertyInfo( (propertyInfo) => { return(propertyInfo.GetCustomAttribute( (ReferencedEntityAttribute refAttribute) => { var propertyName = refAttribute.PropertyName; // If a quote has not been assigned, do not run yet if (!entity.entity.Attributes.Contains(propertyName)) { if (!tracingService.IsDefaultOrNull()) { tracingService.Trace($"Attribute [{propertyName}] not assigned. " + "Available attributes are {0}", String.Join(";", entity.entity.Attributes.Select(kvp => kvp.Key))); } return false; } if (!tracingService.IsDefaultOrNull()) { tracingService.Trace($"[{propertyName}] attribute found"); } if (!(entity.entity.Attributes[propertyName] is EntityReference)) { if (!tracingService.IsDefaultOrNull()) { tracingService.Trace($"Attribute for [{propertyName}] is of type {entity.entity.Attributes[propertyName].GetType().FullName} not EntityReference"); } return false; } // Get the reference and the ID var reference = (EntityReference)entity.entity.Attributes[propertyName]; if (!tracingService.IsDefaultOrNull()) { tracingService.Trace($"{propertyName} Id = {reference.Id.ToString()}"); } var referenceId = reference.Id; return true; }, () => false)); }, () => { throw new ArgumentException(); }); }
public static TResult Retrieve <TEntity, TResult>(this IOrganizationService service, Guid entityId, Func <TEntity, TResult> onFound, Func <string, TResult> onFailure, string[] columns = default(string[]), ITracingService tracingService = default(ITracingService)) { return(typeof(TEntity).GetCustomAttribute( (EntityAttribute entityAttr) => { var columnSet = columns.IsDefault() ? new ColumnSet(true) : new ColumnSet(columns); var xrmEntity = service.Retrieve(entityAttr.LogicalName, entityId, columnSet); var entity = xrmEntity.AsEntity <TEntity>(); if (entity.IsDefault()) { return onFailure("Entity lacks constructors"); } return onFound(entity); }, () => { var msg = "Requested entity missing EntityAttribute"; if (!tracingService.IsDefaultOrNull()) { tracingService.Trace(msg); } return onFailure(msg); })); }
public static TEntity AsEntity <TEntity>(this Entity xrmEntity, ITracingService tracingService = default(ITracingService)) { var validConstructors = typeof(TEntity).GetConstructors() .Where(constructor => constructor.GetParameters().Length == 1) .Where(constructor => constructor.GetParameters().First().ParameterType.IsAssignableFrom(typeof(Entity))); if (!validConstructors.Any()) { if (!tracingService.IsDefaultOrNull()) { tracingService.Trace($"Type [{typeof(TEntity).FullName}] does not have any valid constructors"); } return(default(TEntity)); } var entity = (TEntity)validConstructors.First().Invoke(new object[] { xrmEntity }); return(entity); }