非跟踪查询No-Tracking Queries

有时,可能需要从查询中获取实体,但不能通过上下文跟踪这些实体。Sometimes you may want to get entities back from a query but not have those entities be tracked by the context. 在只读方案中查询大量实体时,这可能会导致更好的性能。This may result in better performance when querying for large numbers of entities in read-only scenarios. 本主题所介绍的方法同样适用于查询使用 Code First 和 EF 设计器创建的模型。The techniques shown in this topic apply equally to models created with Code First and the EF Designer.

新的扩展方法 AsNoTracking 允许以这种方式运行任何查询。A new extension method AsNoTracking allows any query to be run in this way. 例如:For example:

using (var context = new BloggingContext())
{
    // Query for all blogs without tracking them
    var blogs1 = context.Blogs.AsNoTracking();

    // Query for some blogs without tracking them
    var blogs2 = context.Blogs
                        .Where(b => b.Name.Contains(".NET"))
                        .AsNoTracking()
                        .ToList();
}