Hi all,
Using NHibernate I'm trying to get obtain a list of B's where an IList property of B contains a specific instance of A.
The following code should hopefully explain the situation more clearly:
public void test()
{
A a1 = new A();
A a2 = new A();
B b1 = new B();
b1.As = new List<A> { a1 };
// ...database save cut...
using (ISession session = SessionFactory.OpenSession())
{
var result1 = session.CreateCriteria<B>()
.CreateAlias("As", "a_As")
.Add(Restrictions.Eq("a_As.ID", a1.ID))
.List();
var result2 = session.CreateCriteria<B>()
.CreateAlias("As", "a_As")
.Add(Restrictions.Eq("a_As", a1))
.List();
}
}
class A
{
public virtual int ID { get; set; }
}
class B
{
public virtual IList<A> As { get;set;}
}
The second query fails with the error: could not resolve property: a_As of: B
How can I perform this query using object instances without explicitly using the ID properties like in the first query above.
Edit: To expand on this, I have a generic class which performs NHibernate operations with my entities. I've just created an "IsReferenced" method that begins as follows:
public bool IsReferenced(T entity)
{
// Get the types (and their properties) that reference the type in question
var typeProps = from type in typeof(T).Assembly.GetTypes()
let props = type.GetProperties().Where(p => p.PropertyType == typeof(T)).Select(p => p.Name)
let collections = type.GetProperties().Where(p => typeof(IEnumerable<T>).IsAssignableFrom(p.PropertyType)).Select(p => p.Name)
where type.IsClass && !type.IsAbstract && ((props != null && props.Count() > 0) || (collections != null && collections.Count() > 0))
select new { EntityType = type, Properties = props, Collections = collections };
var multiCriteria = NHibernateSession.CreateMultiCriteria();
foreach (var typeProp in typeProps)
{
var criteria = NHibernateSession.CreateCriteria(typeProp.EntityType);
var disjunction = new Disjunction();
foreach (var propName in typeProp.Properties)
{
disjunction.Add(Restrictions.Eq(propName, entity));
}
foreach (var collectionName in typeProp.Collections)
{
throw new NotImplementedException();
}
criteria.Add(disjunction);
multiCriteria.Add(criteria);
}
.....
}
I'm using typeProps to build a MultiCriteria to find any entities anywhere that reference the one specified. It works fine for normal properties, but collection properties are giving me grief. I'm not sure how to go about adding the restriction into the criteria.