示例#1
0
        private object LoadActiveRecord(Type type, object pk, ARFetchAttribute attr, Castle.ActiveRecord.Model model)
        {
            object instance = null;

            if (pk != null && !String.Empty.Equals(pk))
            {
                var pkModel = ObtainPrimaryKey(model);

                var pkType = pkModel.Value.ReturnedClass;

                bool conversionSucceeded;
                var  convertedPk = _converter.Convert(pkType, pk.GetType(), pk, out conversionSucceeded);

                if (!conversionSucceeded)
                {
                    throw new ActiveRecordException(string.Format("ARFetcher could not convert PK {0} to type {1}", pk, pkType));
                }

                if (string.IsNullOrEmpty(attr.Eager))
                {
                    // simple load
                    instance = attr.Required
                                ? AR.Find(type, convertedPk)
                                : AR.Peek(type, convertedPk);
                }
                else
                {
                    // load using eager fetching of lazy collections
                    var criteria = DetachedCriteria.For(type);
                    criteria.Add(Expression.Eq(pkModel.Key, convertedPk));
                    foreach (var associationToEagerFetch in attr.Eager.Split(','))
                    {
                        var clean = associationToEagerFetch.Trim();
                        if (clean.Length == 0)
                        {
                            continue;
                        }

                        criteria.SetFetchMode(clean, FetchMode.Eager);
                    }

                    var result = AR.Execute(type, s => criteria.GetExecutableCriteria(s).List());
                    if (result.Count > 0)
                    {
                        instance = result[0];
                    }
                }
            }

            if (instance == null && attr.Create)
            {
                instance = Activator.CreateInstance(type);
            }

            return(instance);
        }