开发者

Query/Mapping problem using NHibernate

I'm experiencing a problem with a certain query I'm attempting against a simple joined pair of classes, represented in my example below:

Classes:

public class ParentClass
{
   public virtual Guid ParentClassId { get;set;}
   public virtual ChildClass ChildClassRef { get;set;}
}

public class ChildClass
{
    public virtual Guid ChildClassId { get;set;}
    public virtual string ChildCode { get;set;}
}

Fluent Mappings:

public class ParentClassMap : ClassMap<ParentClass>
{
    public ParentClassMap()
    {
        Id(x => x.ParentClassId).GeneratedBy.Guid();
        References<ChildClass>(x => x.ChildClassRef, "ChildClassId").ForeignKey("ChildClassId").Fetch.Join();
    }
}
public class ChildClassMap : ClassMap<ChildClass>
{
    public ChildClassMap()
    {
        Id(x => x.ChildClassId).GeneratedBy.Guid();
        Map(x => x.ChildCode).Not.Nullable();
    }
}

This fails:

DetachedCriteria criteria = DetachedCriteria.For(boType);
criteria.Add(Expression.Eq("ChildClassRef.ChildCode", "ABC"));
ICriteria runnableCriteria = detachedCriteria.GetExecutableCriteria(session);
IList ilistResult = runnableCriteria.List();

with error: "could not resolve property: ChildClassRef.ChildCode".

However, this criteria works:

criteria.Add(Expression.Eq("ChildClassRef.ChildClassId", "931DAF7A-15D1-4B0B-8030-1C113BABC554"));

This, along with other evidence, suggests to me that my开发者_C百科 Fluent Reference mapping is correct (or maybe just slightly flawed).

EDIT: Underlying tables:

ParentClass: ParentClassId, ChildClassId
ChildClass: ChildClassId, ChildCode


I'm a nhibernate newb but I think you would first have to join the table in the query using CreateAlias before being able to query on one of it's properties.


criteria.Add(Expression.Eq("ChildClassRef.ChildCode", "ABC")); 

is different to

criteria.Add(Expression.Eq("ChildClassRef.ChildClassId", "931DAF7A-15D1-4B0B-8030-1C113BABC554"));

cause it references a different property (ChildCode != ChildClassId). On the other hand for better results use CreateCriteria;

var criteria = DetachedCriteria.For<AccountingTransaction>();
criteria.Add(Restrictions.Eq("Period", period));
criteria.CreateCriteria("SimpleDocument", "d", NHibernate.SqlCommand.JoinType.InnerJoin);
criteria.Add(Restrictions.Like("d.DocumentCode", reference, MatchMode.Start));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜