如何使EntityFramework Relation IQueryable?

时间:2013-10-03 14:54:19

标签: c# performance entity-framework

我们假设我有这些课程:

public class Car
{
  public int CarId { get; set} 
  public virtual ICollection<Door> Doors { get; set} 
}

public class Door
{
   public int DoorId { get; set} 
   public decimal Weight { get; set} 
   public int CarId { get; set} 
}

我想做这样的事情

foreach ( var car in db.Cars )
{
   var x = car.Doors.Min(d => d.Weight);
}

正如我在EFTraceLog中看到的,他做了类似的事情 选择*来自Doors,其中CarId = @ ... 并在应用程序服务器上计算“Min”,而不是在db server

上计算

我有很大的车​​和门桌,所以这个操作持续几分钟。 但是,如果我将代码更改为此

foreach ( var car in db.Cars )
{
   var x = db.Doors.Where(d => d.CarId == car.CarId).Min(d => d.Weight);
}

然后几秒钟。

为什么会有这么大的差异以及如何解决它? 这里的问题是编写

要简单得多
var x = car.Doors.Min(d => d.Weight);

然后

var x = db.Doors.Where(d => d.CarId == car.CarId).Min(d => d.Weight);

更新

我们正在使用Entity Framework 5.0

更新2

我试过这些变种,它们很慢

var x = car.Doors.Select(door => door.Weight).Min();
var x = car.Doors.OrderBy(x => x.Weight).Select(x => x.Weight).FirstOrDefault();
var x = car.Doors.OrderBy(x => x.Weight).Select(x => x.Weight).First();
var x = car.Doors.OrderBy(x => x.Weight).FirstOrDefault().Weight;
var x = car.Doors.OrderBy(x => x.Weight).First().Weight;

只有这一个很快

var x = db.Doors.Where(d => d.CarId == car.CarId).Min(d => d.Weight);

更新3

最佳查询产生此sql

declare @p__linq__0 Int32 = cast(N'204' as Int32);

SELECT 
[GroupBy1].[A1] AS [C1]
FROM ( SELECT 
MIN([Extent1].[Weight]) AS [A1]
FROM [dbo].[Doors] AS [Extent1]
WHERE [Extent1].[CarId] = @p__linq__0
) AS [GroupBy1]

2 个答案:

答案 0 :(得分:5)

Linq to Entities仅支持Min而无需额外投影。这意味着您将使用Linq To Objects调用当前的Min(导致您的Doors集合具体化 - 从而生成您在日志中看到的SQL)。

来自MSDN

<强>支持的:

TSource Min<TSource>(this IQueryable<TSource> source)

不支持

TResult Min<TSource, TResult>(this IQueryable<TSource> source,Expression<Func<TSource, TResult>> selector)

您可以尝试使用OrderBySelectFirstOrDefault(支持 )来获得相同的结果:

var min = car.Doors.OrderBy(x => x.Weight).Select(x => x.Weight).FirstOrDefault();

<强>更新

显然Entity Framework不支持Lazy-Load with Projection,这意味着每当你加载引用的实体(在你的情况下为Car.Doors时)框架Lazy-Load所有的数据而你不能选择要加载的属性(Weight)。

这就是两个电话之间差异的原因:

// Accessing 'Doors' thru 'Car' means 'Lazy Load'
car.Doors.Select(x => x.Weight).Min();

但是,

// No 'Lazy Load' involved, hence projection is possible
db.Doors.Where(x => x.CarId == carId).Select(x => x.Weight).Min();

您还可以尝试访问Car.Doors急切加载 Doors

foreach ( var car in db.Cars.Include(x => x.Doors))
{
   var x = car.Doors.Select(x => x.Weight).Min();
}

(我使用了 Servy 提出的Min缩短的替代方案)

答案 1 :(得分:0)

根据haim770's answer,EF不支持投影Min的重载,但您可以先使用Select执行投影,以获得所需的结果:

var minWeight = db.Doors.Select(door => door.Weight).Min();