NHibernate and Manually Assigned Identifiers

Be careful when you use manually assigned identifiers on your entities, because NHibernate looks at them to determine if an object is new or is already in the database.

For example, suppose you have a parent class A which holds a collection of child class B:

using (ISession session = ...)

using (ITransaction tx = session.BeginTransaction())

    A a = session.Load<A>(1);

    B b = new B();

    b.Id = 100;

    a.B.Add(b);

    b.A = a;

    tx.Commit();

}

NHibernate will mistakenly assume that, since b has a non-default id, it is an existing object, and will try to update it, which, of course, will throw an exception, since there is no associated record on the database. In this case, you must explicitly save the b object.

}

                             

3 Comments

  • I got a recipe for this:

    Repeat 1000 times if you're an architect: Never, ever allow to a developer to manually change the identity value.

    Repeat 10000 times if you're a developer: Never, ever change the identity value. My life will be threated if I do so.

    --------------

    Implement The ID property as read-only and change the access to that property for NH as nosetter o field.

  • The water company deal would have led to water costing so much that the average Bolivian would need just about their whole monthly paycheck to buy water, or something like that . ,

  • I bet highly possible it will go faster, with melting tundra being one co2 wild card item. ,

Comments have been disabled for this content.