Hello,
Unfortunately I can't provide you the sourcecode because it belongs to customer but here are main steps I perform:
1. I created class that describes mapping between source property in result of FetchXml Query run to property of entity. Something like following:
public class MappingAttribute : Attribute
{
public string SourceAttribute { get; private set; }
public MappingAttribute(string sourceAttribute)
{
SourceAttribute = sourceAttribute;
}
}
2. I created a base class that contained logic that mapped attributes from source to destination using reflection and attributes:
public abstract class EntityBase
{
protected EntityBase(Entity crmRecord)
{
var mappingProperties =
GetType().GetProperties().Where(p => Attribute.IsDefined(p, typeof(MappingAttribute)));
foreach (var p in mappingProperties)
{
var mappingAttribute =
p.GetCustomAttributes(true).FirstOrDefault(a => a.GetType() == typeof(MappingAttribute)) as MappingAttribute;
if (mappingAttribute == null)
continue;
var crmFieldName = mappingAttribute.SourceAttribute;
if (!crmRecord.Contains(crmFieldName))
continue;
var crmValue = crmRecord[crmFieldName];
if (crmValue is EntityReference)
crmValue = ((EntityReference)crmValue).Name;
else if (crmValue is OptionSetValue)
crmValue = crmRecord.FormattedValues[crmFieldName];
else if (crmValue is DateTime)
crmValue = ((DateTime) crmValue).ToString("MM/dd/yyyy hh:mm tt").Replace('.', '/');
if (!(crmValue is int) && !(crmValue is string) && !(crmValue is Guid))
continue;
p.SetValue(this, crmValue);
}
}
}
In my task I needed only labels so I assumed that target fields always will be string. In your case it could be different so you will have to work on polishing.
3. I inherited my destination class from EntityBase and added property that were marked with my custom attribute:
public class Contact : EntityBase
{
public Contact(Entity crmRecord)
: base(crmRecord)
{
}
[MappingAttribute("firstname")]
public string FirstName { get; set; }
[MappingAttribute("lastname")]
public string LastName { get; set; }
[MappingAttribute("fullname")]
public string fullname { get; set; }
}
4. Use that class with results of fetchxml:
var myContact = new Contact(crmContact);