开发者

NHibernate insert generates updates for collection items

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.


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜