处理非身份主键的生成
目前我们的表没有主键标识。由于互操作性而改变这一点的成本太高。
我正在考虑处理 ObjectContext 的 SavingChanges 事件来设置其值。
(伪代码)
void SavingChanges(context)
{
foreach (var entity in context)
{
if (entity.HasIdentity) continue;
entity.PrimaryKey = GetNextPrimaryKey(entity.Type);
}
}
我只能想到使用单独的连接来完成此操作。是的,GetNextPrimaryKey 将被优化以减少往返次数,但我想这足以解释总体想法。
会起作用吗?我应该尝试一些不同的东西吗?
We currently have tables which don't have a identity for primary key. It would be too costly to change that because of interoperability.
I'm thinking about handling ObjectContext's SavingChanges event to set its values.
(pseudocode)
void SavingChanges(context)
{
foreach (var entity in context)
{
if (entity.HasIdentity) continue;
entity.PrimaryKey = GetNextPrimaryKey(entity.Type);
}
}
I can only think of using a separate connection to accomplish this. And yes, GetNextPrimaryKey would be otimized to reduce the number of roundtrips, but I guess it was suficient to explain the overall idea.
Would it work? Should I try something different?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这取决于 GetNextPrimaryKey 方法中的逻辑。
如果您的方法在多个线程中执行,那么您将有机会将相同的键分配给多个对象。
但是,如果您的 GetNextPrimaryKey 前进您的密钥并始终返回一个新密钥,无论它是否被使用,那么就没有问题。
但如果你的逻辑只是简单地找出最后使用的 key 并执行 key + 1,那么在多线程情况或 Web 应用程序中,你将会遇到冲突。
最好是使用某种存储过程并始终从 SP 返回新密钥,因此在并行执行 GetNextPrimaryKey 时不会出现任何问题。
This depends upon the logic within the method GetNextPrimaryKey.
If your method is executed in multiple threads then you will have chances of same key being assigned to multiple objects.
Buti if your GetNextPrimaryKey advances your key and returns always a new key, regardless of whether it is used or not, then there is no problem.
But if your logic is simply to find out last used key and do key + 1, then in multithreaded situations or web applications, you will have conflicts.
Best would be to use some sort of Stored Procedure and return a new key always from SP, so there will not be any issue in case of parallel execution of GetNextPrimaryKey.