简体   繁体   English

使用NHibernate从父ID获取孩子

[英]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. 我有一个Child类,它没有ParentId属性,但是在数据库中具有必需的外键。 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. 我正在尝试使用NHibernate使用ParentId的Children,但是它抛出一个错误,提示无法解析属性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>

如果您不想拥有ParentId属性,则应在私有字段ParentId中打广告,这样您仍然可以查询它,但是它不是公共的,因此它对应用程序的其余部分不可见。

Use a Native SQL Query : 使用本机SQL查询

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

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 . 要在您的域类中使用不带属性的NHibernate列,请使用可以使用鲜为人知的Noop访问: 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. 我敢打赌,您可以通过映射“多对一”类型的“父代”来使这一过程更加流畅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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