private object LoadActiveRecord(Type type, object pk, ARFetchAttribute attr, ActiveRecordModel model)
{
object instance = null;
if (pk != null && !String.Empty.Equals(pk))
{
PrimaryKeyModel pkModel = ObtainPrimaryKey(model);
Type pkType = pkModel.Property.PropertyType;
bool conversionSucceeded;
object convertedPk = converter.Convert(pkType, pk.GetType(), pk, out conversionSucceeded);
if (!conversionSucceeded)
{
throw new RailsException("ARFetcher could not convert PK {0} to type {1}", pk, pkType);
}
if (attr.Eager == null || attr.Eager.Length == 0)
{
// simple load
instance = ActiveRecordMediator.FindByPrimaryKey(type, convertedPk, attr.Required);
}
else
{
// load using eager fetching of lazy collections
DetachedCriteria criteria = DetachedCriteria.For(type);
criteria.Add(Expression.Eq(pkModel.Property.Name, convertedPk));
foreach (string associationToEagerFetch in attr.Eager.Split(','))
{
string clean = associationToEagerFetch.Trim();
if (clean.Length == 0)
{
continue;
}
criteria.SetFetchMode(clean, FetchMode.Eager);
}
object[] result = (object[]) ActiveRecordMediator.FindAll(type, criteria);
if (result.Length > 0)
instance = result[0];
}
}
if (instance == null && attr.Create)
{
instance = Activator.CreateInstance(type);
}
return instance;
}