BobRock
BobRock

Reputation: 3467

getting first element from nhibernate fetch collection

I have one entity which besides other information holds many images. This is one 2 many. In situation where I need to load just first from that collection to slow loading I have following query which retrieve collection of images.

 List<Entity> data = session.Query<Entity>()
          .Fetch(x=>x.Photos)//here I need only first element
          .Fetch(x=>x.Features)
          .ToList();

Upvotes: 2

Views: 1903

Answers (2)

Asif Mushtaq
Asif Mushtaq

Reputation: 13150

List<Entity> data = session.Query<Entity>()
          .Fetch(x=>x.Photos.FirstOrDefualt())//here I need only first element
          .Fetch(x=>x.Features)
          .ToList();

Upvotes: 1

Pranay Rana
Pranay Rana

Reputation: 176896

Make use of First() or FirstOrDefault() method of th linq wiil do task for you

List<Entity> data = session.Query<Entity>()
           .Fetch(x=>x.Photos.First())//
           .Fetch(x=>x.Features)
           .ToList(); 

or

List<Entity> data = session.Query<Entity>()
               .Fetch(x=>x.Photos.FirstOrDefault())//
               .Fetch(x=>x.Features)
               .ToList(); 

aslo read this before using this methods : When to use .First and when to use .FirstOrDefault with LINQ?

Upvotes: 2

Related Questions