user9124444
user9124444

Reputation:

NHibernate, child entities are not lazy loaded

why are the children eager loaded ?

This is the relation :

public class Order 
{

    private IList<Product> _Product;
    public virtual IReadOnlyCollection<Product> Products { get => _Product.ToList(); }
}

public class Product
{
     private IList<Item> _Item;
     protected internal virtual IReadOnlyCollection<Item> Items { get => _Item.ToList(); }
}

public class Item
{
     private string _name;
     public string Name { get => _name; }

     private decimal _quantity;
     public decimal Quantity { get => _quantity; }
}

Some method that gets the aggregate from DB

void Get(aggregateId)
{
    var q = await Session.GetAsync<TAggregate>(aggregateId, cancellationToken);

    var y = q as Order;

    if (NHibernateUtil.IsInitialized(y.Products)) /// => TRUE
}  

The Configurations for Order and Product

OrderConfiguration :

    mapping
        .HasMany<Product>(Reveal.Member<Order>("Products"))
        .Access.LowerCaseField(Prefix.Underscore)
        .Cascade.AllDeleteOrphan()
        .Not.KeyNullable()
        .Not.KeyUpdate()
        .LazyLoad();

ProductConfiguration

        mapping
            .HasMany<Item>(Reveal.Member<Product>("Items"))
            .LazyLoad()
            .Component(
                composit =>
                {
                    composit
                        .Map(instruction => instruction.Name)
                        .Column("Name")
                        .Not.Nullable();

                    composit
                        .Map(instruction => instruction.Quantity)
                        .Column("Quantity")
                        .Not.Nullable();
                });

Why does NHibernate eager loads all the data instead of waiting for it to be loaded only if needed ?

How can this be made lazy ?

Upvotes: 0

Views: 147

Answers (1)

David Osborne
David Osborne

Reputation: 6791

Your use of ToList() on the _Product and _Item collections is inadvertently triggering the lazy loading.

Upvotes: 1

Related Questions