NHibernate 插入生成集合项的更新
我应该如何配置映射以避免 NHibernate 在插入子实体的外键后立即更新它们?
例如,父类映射如下:
class ParentMap : ClassMap<Parent>
{
public ParentMap()
{
Id(x => x.Id)
.GeneratedBy.Increment();
Map(x => x.Name);
HasMany(x => x.ChildNodes)
.KeyColumns.Add("Parent_id")
.Cascade.All();
}
}
让 Parent
有一堆 Child
对象:
Parent p = new Parent("test");
p.ChildNodes.AddRange(GetSomeDummyNodes());
当我保存父实体时,生成的 SQL 如下所示:
INSERT INTO [Parent] (Name, Id) VALUES (@p0, @p1); @p0 = 'test', @p1 = 0
INSERT INTO [Child] (Name, Id) VALUES (@p0); @p0 = 'child1', @p1 = 0
INSERT INTO [Child] (Name, Id) VALUES (@p0); @p0 = 'child2', @p1 = 1
INSERT INTO [Child] (Name, Id) VALUES (@p0); @p0 = 'child3', @p1 = 2
UPDATE [Child] SET Parent_id = @p0 WHERE Id = @p1; @p0 = 0, @p1 = 0
UPDATE [Child] SET Parent_id = @p0 WHERE Id = @p1; @p0 = 1, @p1 = 0
UPDATE [Child] SET Parent_id = @p0 WHERE Id = @p1; @p0 = 2, @p1 = 0
如果我使用 Guid.Comb作为 Id 列生成器,没有更新,外键立即在 INSERT 语句中设置。但由于我使用的是 Increment
策略(它也在客户端创建 ID,并且没有 SELECT
语句可以从数据库读取 ID 值,所以我不这样做不明白为什么不能立即设置 ID。
How should I configure my mappings to avoid NHibernate updating my child entities' foreign keys right after inserting them?
E.g. Parent class is mapped like this:
class ParentMap : ClassMap<Parent>
{
public ParentMap()
{
Id(x => x.Id)
.GeneratedBy.Increment();
Map(x => x.Name);
HasMany(x => x.ChildNodes)
.KeyColumns.Add("Parent_id")
.Cascade.All();
}
}
Let Parent
have a bunch of Child
objects:
Parent p = new Parent("test");
p.ChildNodes.AddRange(GetSomeDummyNodes());
When I save the parent entity, generated SQL looks like this:
INSERT INTO [Parent] (Name, Id) VALUES (@p0, @p1); @p0 = 'test', @p1 = 0
INSERT INTO [Child] (Name, Id) VALUES (@p0); @p0 = 'child1', @p1 = 0
INSERT INTO [Child] (Name, Id) VALUES (@p0); @p0 = 'child2', @p1 = 1
INSERT INTO [Child] (Name, Id) VALUES (@p0); @p0 = 'child3', @p1 = 2
UPDATE [Child] SET Parent_id = @p0 WHERE Id = @p1; @p0 = 0, @p1 = 0
UPDATE [Child] SET Parent_id = @p0 WHERE Id = @p1; @p0 = 1, @p1 = 0
UPDATE [Child] SET Parent_id = @p0 WHERE Id = @p1; @p0 = 2, @p1 = 0
If I use Guid.Comb as Id column generator, there are no updates, foreign keys are set in INSERT
statements immediately. But since I am using the Increment
strategy (which also creates IDs on the client side, and there is no SELECT
statement which would read the ID value from the database, I don't see why IDs couldn't be set immediately.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您必须查看“反向”映射属性。
I think you'll have to take a look at the 'Inverse' mapping attribute.