Nhibernate queries with duplicate duplication (or fetch)

I encounter unexpected behavior that I don't understand. Of course I can use different ones, but what is the reason?

I have entities (smooth auto-matching):

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 actions):

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

      

request :

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

      

And I have the following result :

enter image description here

+3


source to share


1 answer


When you stand, you are returning a cartesian product when you join a table one-to-many

, in your case 1 x 5 rows. Therefore, if you want to go down this route, you need to add.TransformUsing(Transformers.DistinctRootEntity)

Are you sure you don't want to load any activity and use the goodness of lazy loading to fetch Acts? In most cases, this may be the more efficient way.

Some of them: -



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

      

then you can just call just

foreach(var activity in  ticket.Activities)
{
 // do something here....
}

      

+4


source







All Articles