简体   繁体   中英

NHibernate Child items query using Parent Id

So I have a set up similar to this questions: Parent Child Setup

Everything works great when saving the parent and the children.

However, I seem to have a problem when selecting the children. I can't seem to get all the children with a specific parent.

This fails with: NHibernate.QueryException: could not resolve property: ParentEntity_id of: Test.Data.ChildEntity

Here is my code:

    public IEnumerable<ChildEntity> GetByParent(ParentEntity parent)
    {
        using (ISession session = OrmHelper.OpenSession())
        {

            return session.CreateCriteria<ChildEntity>().Add(Restrictions.Eq("ParentEntity_id ", parent.Id)).List<ChildEntity>();
        }
    }

Any help in building a proper function to get all the items would be appreciated.

Oh, I am using Fluent NHibernate to construct the mappings - version 1 RTM and NHibernate 2.1.2 GA

If you need more information, let me know.

As per you request, my fluent mappings:

            public ParentEntityMap()
    {
        Id(x => x.Id);          
        Map(x => x.Name);           
        Map(x => x.Code).UniqueKey("ukCode");
        HasMany(x => x.ChildEntity).LazyLoad()
            .Inverse().Cascade.SaveUpdate();
    }

    public ChildEntityMap()
    {
        Id(x => x.Id);
        Map(x => x.Amount);
        Map(x => x.LogTime);
        References(x => x.ParentEntity);                
    }

That maps to the following 2 tables:

CREATE TABLE "ParentEntity" (
Id  integer,
Name TEXT, 
Code TEXT,
primary key (Id),
unique (Code)
)

CREATE TABLE "ChildEntity" (
Id  integer,
Amount NUMERIC,
LogTime DATETIME,
ParentEntity_id INTEGER, 
primary key (Id)
)

The data store in SQLite.

return session.CreateCriteria<ChildEntity>()
  .Add(Restrictions.Eq("ParentEntity", parent))
  .List<ChildEntity>();

Just use the parent itself.

In your criteria you should never refer to the column name but to the property name. Change "ParentEntity_id" to "ParentEntity.Id " and that should solve it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM