如何在Entity Framework 5中获取SQL 2008的下一个主键 [英] How can I get the next Primary Key for SQL 2008 in Entity Framework 5

查看:50
本文介绍了如何在Entity Framework 5中获取SQL 2008的下一个主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Entity Framework 5连接来连接到SQL 2008服务器来为我的应用程序执行数据库处理。



我在Visual Studio 2013中使用MVC4我的问题是关于由SQL本身增加的主键字段,我是否有可能找到数据库接下来要使用的ID。



之所以我不能找到最后一项和+1是因为如果我的表包含项目1,2,3,4和5,删除项目5然后添加另一项将使下一项目成为项目6,而不是5(因为我在SQL中使用身份规范,但必须使用)。



我找不到任何方法,例如Item.ID.GetNextIdentity( )或类似的东西,看了很多类似的问题,但没有用。



任何帮助将不胜感激



先谢谢



Krishanpal Singh

决方案
答案是很简单的。你不能。由于网络固有的并行访问,您无法查询下一个ID,然后指望它在保存数据时可用。



但是你可以做的是查询附加表COUNTERS,其中您将保留当前上次保存的项目,并且每次查询该表以获取新ID时,它应该真正插入一个具有ID和空数据的条目(NULLS),您将在稍后填写并且相同的get将更新计数器。



这绝不是完整的证明,如果用户决定在提交前取消,你最终会得到空行。



一般情况下,您不需要该值用于用户交互 - 它应该在您的插入中自动添加,然后刷新网格(此时您将有更新的ID)。如果您不想刷新整个网格,请至少从插入中返回新ID的标量值并更新当前行) - 如果您必须向用户显示一些数字,请使用您控制的非PK编号(以及可以是最大+1)。



如果这有帮助,请花时间接受解决方案。


I am using an Entity Framework 5 connection to connect to a SQL 2008 server to do database handling for my application.

I am using MVC4 in Visual Studio 2013 and my question is regarding Primary Key fields that are incremented by the SQL itself, is it possible at all for me to be able to find the ID that will be used next by the database.

The reason why I cannot just find the last item and +1 is because if my table contains items 1,2,3,4 and 5, removing item 5 then adding another will make the next item become item 6, rather than 5 again (As I use the Identity Specification in SQL, but this must be used).

I cannot find any method such as Item.ID.GetNextIdentity() or something like that and have looked through as many similar questions like this but to no avail.

Any help would be appreciated

Thanks in Advance

Krishanpal Singh

解决方案

The answer is very simple. You can't. Because of the web inherent parallel access you cannot query the next ID and then count on it being available at the time of the saving data.

What you can do however is query additional table COUNTERS in which you will keep current last saved item and each time the table is queried for new ID it should really insert one entry which will have ID and empty data (NULLS) which you will fill later and that same get will update counters.

This is by no means full proof and you will end up with empty rows if users decide to cancel before commiting.

In general, you should't need that value for user interactions - it should be auto-added on your insert and then the grid refreshed (at which point you will have ID for updates). If you don't want to refresh whole grid at least return scalar value of new ID from the insert and update your current row) - if you have to show some number to the user, use non-PK number that you control (and that CAN be max +1).

If this helps, please take time to accept the solution.


这篇关于如何在Entity Framework 5中获取SQL 2008的下一个主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆