3

I meet unexpected behavior and It's not clear for me. Of course I can use distinct, but what is a reason?

I have entities (fluent auto-mapping):

public class Ticket
{
    public virtual int Id { get; set; }
    public virtual string Title { get; set; }
    public virtual IList<Activity> Activities { get; set; }
}

public class Activity
{
    public virtual int Id { get; set; }
    public virtual string Title { get; set; }
    public virtual Ticket Ticket { get; set; }
}

Test data (1 ticket with 5 activities):

new Ticket { Id = 1, Activities = new List<Activity>
    {
        new Activity(), new Activity(), new Activity(), new Activity()
    };

The query:

var report = GetSessionFactory()
    .OpenSession()
    .QueryOver<Ticket>()
    .JoinAlias(ticket => ticket.Activities, () => activity)
    .List<Ticket>();

And I have the following result:

enter image description here

1 Answer 1

4

As you stand you are returning a cartesian product as you are joining a one-to-many table, in your case 1 x 5 rows. So if you want to go down this route then you will need to add .TransformUsing(Transformers.DistinctRootEntity)

Are you sure you don't want to load an activity and use the goodness of lazy loading to retrieve the Activities? In most cases this might be the more efficient way.

Somehing like:-

var ticket = session.QueryOver<Ticket>.Where(w => w.Id == id).SingleOrDefault();
OR
var ticket = session.Get<Ticket>(1);

then you can just call simply

foreach(var activity in  ticket.Activities)
{
 // do something here....
}
Sign up to request clarification or add additional context in comments.

4 Comments

I see. But what is a reason? Why NHibernate does not do it implicitly?
Pass. That's a question for the nh development team. To be honest lazy loading is your friend.
What is suggested is leading to SELECT N+1
make sure you have batch-size enabled and this does not lead to SELECT N+1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.