c# - 如何让 Entity Framework 为给定的代码调用 DB 一次?

标签 c# entity-framework

我必须检查 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 个调用

  1. 首先是 pcimages.Any()
  2. 第二个用于 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/

相关文章:

c# - 将数据网格导出到 excel asp

c# - Selenium Webdriver 与 Shadow DOM

c# - 如何处理不允许在c#中的接口(interface)中定义类型

asp.net - 无法添加方法 OnModelCreating

entity-framework - 使用 Breeze 维护插入订单

entity-framework - 如何让 Appstats 同时显示小操作和读取操作?

c# - 目录的 GetTempFileName 函数?

c# - DataGridView 双下划线单元格

.net - Entity Framework 4.0 不适用于计算属性

c# - Entity Framework : am I supposed to modify migration classes?