1
votes

I've looked around stack overflow and can't find an answer for this anywhere.

Say I have a class Man

class Man
{
    protected virtual ICollection<Cat> Cats {get; set;}
}

class ManMapping : ClassMap<Man>
{
    HasMany(Reveal.Member<Man, IEnumerable<Cat>>("Cats"))
            .KeyColumn("ManId")
            .Cascade.All();
}

I know that if it was a public property I could use .fetch() to eager load it, but I can't find a way to eager load the collection when it's set to protected.

I should also mention that I'm looking to eager load in code on a case by case basis, not in the mappings.

Thanks.

1
Eager loading depends on the query type, what type are you using (HQL, Criteria, QueryOver, Linq)?cremor

1 Answers

3
votes

I've only just briefly tested this and can't confirm it works 100% yet, but you should be able to use reflection to get the property and create an Expression that would eager load the property.

First, get the property through reflection:

var catsProperty = typeof(Man).GetProperty("Cats", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

Then, create an expression argument that points to a Man, and an Expression that gets the property:

var expressionArgument = Expression.Parameter(typeof(Man), "m");
var propertyGetter =
    Expression.Lambda<Func<Man, IEnumerable<Cat>>>(
        Expression.Property(expressionArgument, catsProperty),
        expressionArgument);

Then use that in your linq query:

var man =
    session.Query<Man>()
        .Fetch(propertyGetter)
        .First();