问题描述
为什么实体框架的DbContext.Find()生成与选择前2名和派生表的查询?根据定义,查询查找由主键应该是唯一的。
Why does the Entity Framework's DbContext.Find() generate a query with select top 2 and a derived table? By definition, the query is looking up by primary key which should be unique.
推荐答案
查找
首先检查是否与给定键的实体已经在上下文中。如果不是查询数据库。可能它使用在这种情况下LINQ查询使用的SingleOrDefault
。 的SingleOrDefault
转化为 SELECT TOP 2
来能如果结果有多个实体,抛出异常。
Find
checks first if the entity with the given key is already in the context. If not it queries the database. Possibly it uses in this case a LINQ query using SingleOrDefault
. SingleOrDefault
translates to SELECT TOP 2
to be able to throw an exception if the result has more than one entity.
那么,为什么不查找
使用 FirstOrDefault
(这将转化为 SELECT TOP 1
)。我不知道,但我猜想,查找
要检查的实体是在数据库中非常独特。它应该 - 因为它是该查询使用主键 - 但模型和数据库可以是不同步的,因为有人改变主键数据库中的,例如:加入一列在数据库中的复合键,但不是在模型。
So, why doesn't Find
use FirstOrDefault
(which would translate to SELECT TOP 1
). I don't know, but I would guess that Find
wants to check that the entity is really unique in the database. It should - because it's the primary key the query uses - but model and database could be out of sync because someone changed the primary key in the database, for example: added a column to a composite key in the database but not in the model.
真的只是一个假设。只有EF的开发团队也许能回答什么是确切的原因。
Really just a hypothesis. Only EF development team probably can answer what's exactly the reason.
修改
如果我这样做,因为上述(添加列组合键的数据库,并添加一条记录的第一个键列中的值相同),并调用然后查找
,我得到的异常...
If I do this as described above (add column to composite key in DB and add a record with the same value in the first key column) and call then Find
, I get the exception...
序列包含多个元素
...这堆栈跟踪:
//...
System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
System.Data.Entity.Internal.Linq.InternalSet`1.FindInStore(
WrappedEntityKey key, String keyValuesParamName)
System.Data.Entity.Internal.Linq.InternalSet`1.Find(Object[] keyValues)
System.Data.Entity.DbSet`1.Find(Object[] keyValues)
因此,它看起来是查找
确实使用的SingleOrDefault
。
这篇关于为什么实体框架的DbContext.Find()生成与选择前2名的查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!