开发者

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

开发者 https://www.devze.com 2023-03-12 15:17 出处:网络
I have to check existance of PatientChartImage in PatientChartImage table.If Images exists i amassigning it to a existing object. I am using the following code in EF 4.0

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.


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();


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.


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

isNewImage = pcimage != null;


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;  
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号