简体   繁体   中英

NHibernate - load sql query to entity

Basically, I need to set a property to the results of a query that uses data from the parent object.

With the domain model below, I need to set the C property of EntityB using data from both EntityA and EntityB.

Also, I need to set the A property of EntityB to be the actual instance of EntityA that is its parent.

Query:

Set EntityB.C = (select * from EntityC where SomeProperty = EntityB.SomeProperty and AnotherProperty = EntityB.A.AnotherProperty);

SomeProperty and AnotherProperty are not just keys.

class EntityA
{
    public IList<EntityB> B
    {
        get;
        set;
    }

}

class EntityB
{
    public EntityA A
    {
        get;
        set;
    }


    public EntityC C
    {
        get;
        set;
    }
}

class EntityC
{
    ...
}

I need a way to execute code (to run the query and assign to property) for each entity returned. I came close using the onload method of an interceptor, but I am looking for another way. Perhaps using a Result Transformer or a Projection?

First of all, if you're using NHibernate properly, the properties and associations should be automatically done for you by the framework. If they're not, then you don't have it set up correctly...

As for doing a query in a property... this is usually not recommended (abstract it into a utility class, or at the very least a function call), but I do remember seeing some way on here how to do it.

There are actually two questions.

Question 1: How to have a property that is loaded by some query?

Ask your self if it really needs to be in the entity. Consider to have a DTO (data transfer object) that holds data from different entities and queries instead.

If you're sure that you need this property in the entity, take a look at formulas for single ended properties and filters for collections.

I can't provide more detailed information, because your question is highly general, and it depends on the actual problem. But you should find a solution by starting with the given links.

Question 2: How can I have a property pointing to the parent?

Very easy: By just implementing the property and map the collection of children (B) "inverse=true" . Implement your entities the way that they consistently point to the correct parent.

Why is NH not doing this for you? Because NH's responsibility is only to persist your entities to the database. NH does not make any changes on the data by its own. This is responsibility of your business logic.

Note: your application should also be able to run without NH, eg in a unit test. So relations should be managed in your code.

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