kirps
kirps

Reputation: 1355

Fluent NHibernate: Getting a "could not initialize collection" error while debugging an NUnit test in SharpDevelop

I am getting the following error when attempting to work with an unremarkable object with a collection of other objects as a member when using NHibernate as my ORM tool. When the top-level object doesn't have any objects in said collection I am getting an error like "Could not initialize a collection: (a ton of SQL)". I know that the table it is referencing is empty as should be the collection, but NHibernate seems to be attempting to fill it an is then throwing an exception because there is no data.

I would expect the collection to simply be null or empty rather than halting the execution of the program, this looks like an NHibernate error to me, but it is possible I improperly wrapped the ORM objects etc. as I am relatively new to the technology. My mapping is attached below. The _holdings collection is what is throwing the error.

public class FundMap : ClassMap<Fund>
{
    public FundMap() 
    {
        Id(x => x._fundID).GeneratedBy.Identity();
        Map(x => x._cik);
        Map(x => x._fundName);
        //TODO: get correct handling of HasMany relationships.
        HasMany(x => x._holdings)
            //.Inverse()
            .Cascade.All();
            //.Cascade.None();
    }
}

Upvotes: 2

Views: 2749

Answers (1)

Firo
Firo

Reputation: 30813

NH always attaches its own list implementation to the object which lazy loads the contents on first access. It only knows after querying the db that the collection is really empty.

My guess is that the mapping of Holding doesnt match the mapping of the hasmany. consider something like this:

public HoldingMap()
{
    References(x => x.Fund, "f_id");
}

public FundMap()
{
    HasMany(x => x._holdings)
        //.Column("fund_id")     // the default
        .Cascade.All();
}

the Hasmany doesnt have the right foreign key column and fails to load the Holdings. You can solve it with specifying the column explicitly

    HasMany(x => x._holdings)
        .Column("f_id")     // same as in Holding
        .Cascade.All();

Upvotes: 3

Related Questions