使用指定的 PK 创建新记录 - Castle ActiveRecord
我有一个带有 GUID 主键的表。在 ActiveRecord 中,它是使用 PrimaryKeyType.GuidComb 进行设置的。是否可以使用手动分配的 PK 创建此记录?如果我在记录中设置主键并运行 Create(),则会分配一个新 ID。如果我运行 Save() 我会收到一个错误(正如人们所期望的)。
原因: 该表位于两个数据库中。有时需要在这两个数据库之间复制记录。我想在记录在数据库之间移动时保留 ID。
I have a table with a GUID primary key. In ActiveRecord it is setup with a PrimaryKeyType.GuidComb. Is it possible to create this record with a manually assigned PK? If I set the primary key in the record and run Create() a new ID is assigned. If I run Save() I get an error (as one would expect).
The why:
This table is in two databases. Records need to be copied between these two databases on occasion. I would like to retain the ID as the record moves across the DBs.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不可以。主键要么是生成的(例如 GuidComb),要么是手动分配的,不能两者兼而有之。您可以创建从定义除主键之外的所有属性的基类继承的两个类,然后这两个类中的每一个都将其主键定义为分配或生成。但我建议在这里使用 SQL,因为单个
INSERT INTO ... SELECT
比使用 NHibernate/ActiveRecord 更有效。No. A primary key is either generated (e.g. GuidComb) or manually assigned, it can't be both. You could create two classes that inherited from a base class defining all properties except the primary key, then each of these two classes would define their primary key as assigned or generated. But I'd recommend using SQL here, as a single
INSERT INTO ... SELECT
will be more efficient than using NHibernate/ActiveRecord.我最终将 PrimaryKeyType 设置为“Assigned”。然后我用一个重写的Create函数来处理它:
最好把它放在OnSave中,但主键不能在拦截器中修改。这适用于我的应用程序,但是只有显式创建对象时才会调用此代码。如果对象是通过级联创建的,则不起作用。
I ended up setting the PrimaryKeyType to Assigned. Then I handled it with an overrided Create function:
It would have been better to put this in OnSave, but the primary key cannot be modified in the interceptor. This works for my application, however this code will only be called if the object is explicitly created. It will not work if the object is created by cascade.