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); }
public override bool IsValid(object instance, object fieldvalue) { if (fieldvalue == null) { return(true); } var instanceType = NHibernateUtil.GetClass(instance); var model = AR.Holder.GetModel(instanceType); if (model == null) { throw new ValidationFailure("Couldn't figure out the primary key for " + instanceType.FullName + " so can't ensure the uniqueness of any field. Validator failed."); } return(AR.Execute(instanceType, session => { var origflushmode = session.FlushMode; session.FlushMode = FlushMode.Never; try { var criteria = session.CreateCriteria(model.Type) .SetProjection(Projections.RowCount()); if (Property.Name.Equals(model.PrimaryKey.Key, StringComparison.InvariantCultureIgnoreCase)) { // IsUniqueValidator is on the PrimaryKey Property, simplify query criteria.Add(Restrictions.Eq(Property.Name, fieldvalue)); } else { var id = instance.GetType().GetProperty(model.PrimaryKey.Key).GetValue(instance, null); ICriterion pKeyCriteria = (id == null) ? Restrictions.IsNull(model.PrimaryKey.Key) : Restrictions.Eq(model.PrimaryKey.Key, id); criteria.Add(Restrictions.And(Restrictions.Eq(Property.Name, fieldvalue), Restrictions.Not(pKeyCriteria))); } return criteria.UniqueResult <int>() == 0; } finally { session.FlushMode = origflushmode; } })); }