为什么没有实体框架6只选择SCOPE_IDENTITY()插入后?实体、框架、SCOPE_IDENTITY

2023-09-04 22:44:00 作者:与喜欢撞个满怀

当你节省了使用EF 6.1,下面的SQL code生成并执行的实体:

When you're saving an entity using EF 6.1, the following SQL Code is generated and executed:

exec sp_executesql N'INSERT [dbo].[Customers]([Name], [FirstName])
VALUES (@0, @1)
SELECT [CustomerId]
FROM [dbo].[Customers]
WHERE @@ROWCOUNT > 0 AND [CustomerId] = scope_identity()',N'@0 nvarchar(max) ,@1 nvarchar(max) ',@0=N'Wenk',@1=N'Manuel'

据我所知,该插入/选择完成后,要保存后检索CustomerID列immediatley的价值。据我所知,SCOPE_IDENTITY()返回值,那么为什么没有像

I understand, that the insert/select is done, to retrieve the value of the CustomerId Column immediatley after saving. As far as I know, scope_identity() returns the value, so why isn’t there something like

SELECT scope_identity()

,而不是所有的东西需要物理读?

instead of all that stuff that require physical reads?

干杯, 曼努埃尔

推荐答案

正确的。 SCOPE_IDENTITY()是那里得到生成的客户ID 的值,因此EF可以使用它作为实体键。我想,但我猜测,因为它没有记录,在 SELECT 客户完成表,以确保检索 SCOPE_IDENTITY()真的是关系到客户ID 。可能有这样的情况,一个插入触发多个插件,以便 SCOPE_IDENTITY()被分配到其他记录。

Correct. scope_identity() is there to get the generated CustomerId value, so EF can use it as entity key. I think, but I have to guess because it's not documented, the SELECT is done on the Customer table to make sure the retrieved scope_identity() really is related to CustomerId. There may be cases that an INSERT triggers more inserts so scope_identity() is allotted to another record.

第二个原因来查询客户表是在一个方法,还可以添加计算列在SELECT子句生成这个查询。这可能是无论如何要查询的实体表更方便。

A second reason to query the Customer table is that this query is generated in one method that may also add computed columns to the SELECT clause. It was probably more convenient to query the entity table anyway.

,其中@@ ROWCOUNT> 0 子句添加,以确保行的预期数量是受插入语句。在EF的源$ C ​​$ C有一个注释:

The WHERE @@ROWCOUNT > 0 clause is added to make sure that the expected number of rows is affected by the INSERT statement. In EF's source code there is a comment:

请注意,我们的行数过滤,以确保如果没有行被修改没有返回行。

Note that we filter on rowcount to ensure no rows are returned if no rows were modified.