为什么Find方法生成TOP(2)查询?

Sel*_*enç 12 c# sql entity-framework

我正在使用Entity Framework 6.1,我有一个这样的代码:

Brand b;
using(var ctx = new KokosEntities())
{
      try
      {  
          b = ctx.Brands.Find(_brands[brandName].Id);
          return b;
      }
      catch (Exception ex)
      {
           _logger.Log(LogLevel.Error, ex);
      }
 }
Run Code Online (Sandbox Code Playgroud)

这会产生:

 N'SELECT TOP (2) 
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name], 
[Extent1].[OpenCartId] AS [OpenCartId]
FROM [dbo].[Brands] AS [Extent1]
WHERE [Extent1].[Id] = @p0',N'@p0 int'
Run Code Online (Sandbox Code Playgroud)

Find方法返回单个结果,但它生成一个TOP(2)查询而不是1.为什么?

注意:我确定我正确Id地传递给方法,是的,Id是主键.

Hab*_*bib 13

如果您查看以下文档DbSet<TEntity>.Find Method:

查找具有给定主键值的实体.

我看了一下Find方法的源代码,发现:

/// <exception cref="T:System.InvalidOperationException">Thrown if multiple entities exist in the context with the primary key values given.</exception><exception cref="T:System.InvalidOperationException">Thrown if the type of entity is not part of the data model for this context.</exception><exception cref="T:System.InvalidOperationException">Thrown if the types of the key values do not match the types of the key values for the entity type to be found.</exception><exception cref="T:System.InvalidOperationException">Thrown if the context has been disposed.</exception>
    public virtual TEntity Find(params object[] keyValues)
    {
      return this.GetInternalSetWithCheck("Find").Find(keyValues);
    }
Run Code Online (Sandbox Code Playgroud)

因此,在多个实体的情况下,该方法将抛出InvalidOperationException.

如果在给定主键值的上下文中存在多个实体,则抛出该异常

在内部呼叫Find不会转化为Single/SingleOrDefault; 相反,一个简单的循环用于检查多个实体.

由于该方法特定于主键,因此在多个实体的情况下应该抛出异常.这就是为什么它生成一个查询来选择至少两个记录.与Single通话类似.

  • +1来源,而不是猜测. (2认同)

Dan*_*ite 9

我猜是在转换为Single电话或看起来像它的东西的掩护下.在这种情况下,LINQ希望确保只有1个结果.如果返回了2条记录,则可以抛出.