Rohit Raghuvansi
Rohit Raghuvansi

Reputation: 2864

How to make Entity Framework to call DB just once for the given code?

I have to check existance of PatientChartImage in PatientChartImage table.If Images exists i am assigning it to a existing object. I am using the following code in EF 4.0

IEnumerable<PatientChartImage> pcimages = from pcImage in context.PatientChartImages
                                        where pcImage.PatientImageID == id
                                        select pcImage;
if (pcimages.Any())
{
   pcimage = pcimages.First();                                        
   isNewImage = false;
}
else
{ 
   isNewImage = true; 
}

Sql Profiler shows 2 calls

  1. first is for pcimages.Any()
  2. second is for pcimages.First()

How can i make this code to call DB only Once.

Upvotes: 1

Views: 76

Answers (4)

Bueller
Bueller

Reputation: 2344

call pcimages.FirstOrDefault() then check if this is null before doing you processing.

something like this

pcimage = pcimages.FirstOrDefault();
if (pcimage != null) {    
   isNewImage = false;
} else {     
   isNewImage = true;  
} 

Upvotes: 0

taylonr
taylonr

Reputation: 10790

var pcimage = (from pcImage in context.PatientChartImages
                                        where pcImage.PatientImageID == id
                                        select pcImage).FirstOrDefault();

isNewImage = pcimage != null;

Upvotes: 1

CodingGorilla
CodingGorilla

Reputation: 19842

How about doing something like this:

pcimage = pcimages.FirstOrDefault();
isNewImage = pcimage != null;

Calling first or default will return null if there are no available images, or the first image in the query sequence. This should result in just a single DB hit.

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 160892

Use FirstOrDefault() instead:

Returns the first element of a sequence, or a default value if the sequence contains no elements.

PatientChartImage pcimage = (from pcImage in context.PatientChartImages
                                  where pcImage.PatientImageID == id
                                  select pcImage).FirstOrDefault();
isNewImage = pcimage!=null;

Personally I would use lambda syntax in this case:

PatientChartImage pcimage = context.PatientChartImages
                                   .Where( x => x.PatientImageID == id)
                                   .FirstOrDefault();

Upvotes: 2

Related Questions