Hemanshu Bhojak
Hemanshu Bhojak

Reputation: 17288

Get child from parent id using NHibernate

I have a class Child which does not have a ParentId property but has the required foreign key in the database. I am trying to get the Children using the ParentId using NHibernate but it is throwing an error saying that could not resolve property ParentId.

public class Parent
{
     public int ParentId{ get; set; }

     public string Name{ get; set; }
}

public class Child
{
     public int ChildId{ get; set; }

     public string Name{ get; set; }
}

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="SomeAssembly"
                   namespace="SomeAssembly.SomeNamespace">
    <class name="Parent" lazy="false" table="Parents">
        <id name="ParentId">
            <generator class="native" />
        </id>
        <property name="Name" />
    </class>

    <class name="Child" lazy="false" table="Children">
        <id name="ChildId">
            <generator class="native" />
        </id>
        <property name="Name" />
    </class>
</hibernate-mapping>

Upvotes: 1

Views: 765

Answers (3)

jyoungdev
jyoungdev

Reputation: 2674

To use a column with NHibernate without a property in your domain class, use can use the lesser-known noop access: http://ayende.com/Blog/archive/2009/06/10/nhibernate-ndash-query-only-properties.aspx.

Something like this (haven't tried it myself):

<property name="ParentId" access="noop" />

I bet you could make this more slick by mapping a many-to-one of type Parent instead.

Upvotes: 1

Jamie Ide
Jamie Ide

Reputation: 49301

Use a Native SQL Query:

return session.CreateSQLQuery("select * from ChildTable where ParentId = ?")
    .AddEntity(typeof(Child))
    .SetInt32(0, parentId)
    .UniqueResult<Child>();

Upvotes: 1

dmonlord
dmonlord

Reputation: 1390

If you don't want to have a ParentId property, you should ad a private field ParentId, then you can still query it, but it's not public, so it's not visible to the rest of your application.

Upvotes: 1

Related Questions