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
通话类似.