我必须检查 PatientChartImage 表中是否存在 PatientChartImage。如果图像存在,我将其分配给现有对象。我在 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 显示 2 个调用
- 首先是 pcimages.Any()
- 第二个用于 pcimages.First()
如何让这段代码只调用一次数据库。
最佳答案
使用FirstOrDefault()
相反:
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;
在这种情况下,我个人会使用 lambda 语法:
PatientChartImage pcimage = context.PatientChartImages
.Where( x => x.PatientImageID == id)
.FirstOrDefault();
关于c# - 如何让 Entity Framework 为给定的代码调用 DB 一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6344181/