使用指定的 PK 创建新记录 - Castle ActiveRecord

发布于 2024-09-28 06:19:55 字数 226 浏览 1 评论 0原文

我有一个带有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

予囚 2024-10-05 06:19:55

不可以。主键要么是生成的(例如 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.

鹿童谣 2024-10-05 06:19:55

我最终将 PrimaryKeyType 设置为“Assigned”。然后我用一个重写的Create函数来处理它:

    public override void Create() {
        if (ID == default(Guid)) ID = GUIDGenerator.Generate();
        base.Create();
    }

最好把它放在OnSave中,但主键不能在拦截器中修改。这适用于我的应用程序,但是只有显式创建对象时才会调用此代码。如果对象是通过级联创建的,则不起作用。

I ended up setting the PrimaryKeyType to Assigned. Then I handled it with an overrided Create function:

    public override void Create() {
        if (ID == default(Guid)) ID = GUIDGenerator.Generate();
        base.Create();
    }

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文