问题
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.
回答1:
I think you'll have to take a look at the 'Inverse' mapping attribute.
HasMany(x => x.ChildNodes)
.Inverse()
.KeyColumns.Add("Parent_id")
.Cascade.All();
来源:https://stackoverflow.com/questions/4285386/nhibernate-insert-generates-updates-for-collection-items