C# 如何使实体框架对给定代码只调用一次DB?
我必须在PatientChartImage表中检查PatientChartImage是否存在。如果存在图像,我将其分配给现有对象。我在EF4.0中使用以下代码C# 如何使实体框架对给定代码只调用一次DB?,c#,entity-framework,C#,Entity Framework,我必须在PatientChartImage表中检查PatientChartImage是否存在。如果存在图像,我将其分配给现有对象。我在EF4.0中使用以下代码 IEnumerable<PatientChartImage> pcimages = from pcImage in context.PatientChartImages where pcImage.PatientImageID == id
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;
}
IEnumerable pcimages=来自context.PatientChartImages中的pcImage
其中pcImage.PatientImageID==id
选择pcImage;
if(pcimages.Any())
{
pcimage=pcimages.First();
isNewImage=false;
}
其他的
{
isNewImage=true;
}
Sql分析器显示2个调用
PatientChartImage pcimage = context.PatientChartImages
.Where( x => x.PatientImageID == id)
.FirstOrDefault();
改用:
返回数组的第一个元素
序列,或默认值(如果
序列不包含任何元素
就我个人而言,我会在这种情况下使用lambda语法:
PatientChartImage pcimage = context.PatientChartImages
.Where( x => x.PatientImageID == id)
.FirstOrDefault();
这样做怎么样:
pcimage = pcimages.FirstOrDefault();
isNewImage = pcimage != null;
如果没有可用图像或查询序列中的第一个图像,则调用first或default将返回null。这应该只会导致一次DB命中 这样做怎么样:
pcimage = pcimages.FirstOrDefault();
isNewImage = pcimage != null;
var pcimage = (from pcImage in context.PatientChartImages
where pcImage.PatientImageID == id
select pcImage).FirstOrDefault();
isNewImage = pcimage != null;
如果没有可用图像或查询序列中的第一个图像,则调用first或default将返回null。这应该只会导致一次DB命中 调用pcimages.FirstOrDefault(),然后在处理之前检查该值是否为null
var pcimage = (from pcImage in context.PatientChartImages
where pcImage.PatientImageID == id
select pcImage).FirstOrDefault();
isNewImage = pcimage != null;
像这样的
pcimage = pcimages.FirstOrDefault();
if (pcimage != null) {
isNewImage = false;
} else {
isNewImage = true;
}
调用pcimages.FirstOrDefault(),然后在进行处理之前检查该值是否为null 像这样的
pcimage = pcimages.FirstOrDefault();
if (pcimage != null) {
isNewImage = false;
} else {
isNewImage = true;
}
+1:你的答案比我的答案快57秒(代码完全相同)1:你的答案比我的答案快57秒(代码完全相同)