/// <summary>
/// Visit Node
/// </summary>
protected virtual Object CreateAndPopulate(NodeContext nodeContext)
{
var node = nodeContext.Node;
var nodeInfo = _mappingContext.VisitNode(nodeContext);
if (nodeInfo.Ignore)
{
return(null);
}
node = nodeInfo.Node ?? node;
if (nodeInfo.NodeRefId != null)
{
return(_mappingContext.RefMap[nodeInfo.NodeRefId]);
}
var metadataStore = _mappingContext.MetadataStore;
EntityType entityType;
Type objectType;
if (nodeInfo.ServerTypeNameInfo != null)
{
var clientEntityTypeName = nodeInfo.ServerTypeNameInfo.ToClient(metadataStore).StructuralTypeName;
entityType = metadataStore.GetEntityType(clientEntityTypeName);
objectType = entityType.ClrType;
if (!nodeContext.ObjectType.IsAssignableFrom(objectType))
{
throw new Exception("Unable to convert returned type: " + objectType.Name + " into type: " +
nodeContext.ObjectType.Name);
}
nodeContext.ObjectType = objectType;
}
else
{
objectType = nodeContext.ObjectType;
entityType = metadataStore.GetEntityType(objectType);
}
// an entity type
nodeContext.StructuralType = entityType;
var keyValues = entityType.KeyProperties
.Select(p => node[p.NameOnServer].ToObject(p.ClrType))
.ToArray();
var entityKey = EntityKey.Create(entityType, keyValues);
var entity = _mappingContext.EntityManager.GetEntityByKey(entityKey);
if (entity == null)
{
entity = (IEntity)Activator.CreateInstance(objectType);
entity.EntityAspect.EntityType = entityType;
}
// must be called before populate
if (nodeInfo.NodeId != null)
{
_mappingContext.RefMap[nodeInfo.NodeId] = entity;
}
_mappingContext.Entities.Add(entity);
return(PopulateEntity(nodeContext, entity));
}