Many to many - composite key and multiple session

Antoine's Avatar

Antoine

28 Oct, 2010 10:08 AM via web

I try to understand nHibernate and Fluent, when using Many to Many relationship.

Imagine the following tables :

  • Post (id, title, content)
  • Tag (id, name)
  • PostTags (idTag, idPost)

PostTags have a composite key (idtag, idpost).

I want to do the following things with the NH objects :

Tag t1 = new Tag("foo").Save(); // created with a session A (always open, attached to the object)

Tag t2 = new Tag("bar").Save(); // created with a session B (always open, attached to the object)

Post p = new Post(1, "my title", "my content").Save(); // created with a session C (always open, attached to the object)

p.AddTag(t1);

t2.AddPost(p);

Assert.AreEqual(2, p.Tags.Count);
Assert.AreEqual(1, t1.Posts.Count);
Assert.AreEqual(1, t2.Posts.Count);

p.Delete(t1);

Assert.AreEqual(1, p.Tags.Count);

Can you please give me the code of :

  • The hibernate entities, and the mapping (with the composity key, iset or ibags, etc).
  • The method AddTag and the method AddPost (with the explanation when manipuling multi session - refresh, merge etc.).

This example will really help me to understand nHibernate. I read lot of post about nhibernate, but revolving this example will help me a lot.

Sincerely,

Antoine

  1. Support Staff 2 Posted by James Gregory on 05 Nov, 2010 01:52 PM

    James Gregory's Avatar

    What do you mean "created with a session A (always open, attached to the object)"? A session should not be attached to an object, unless I'm misunderstanding your description.

    If you have an entity created with a different session as the one you're trying to save it with, you'll need to do a session.Attach(entity) first to make the new session aware of it.

  2. 3 Posted by Antoine on 05 Nov, 2010 02:15 PM

    Antoine's Avatar

    It was just an example. The goal is to understand how to manipulate entities created in different session.

    The session.Attach syntax is interesting, but I don't find it (I use NH2.1). Do you mean Merge or Refresh instead of Attach ?

    Thanks a lot,

    Antoine

  3. Support Staff 4 Posted by James Gregory on 05 Nov, 2010 02:26 PM

    James Gregory's Avatar

    Sorry, that was my mistake. I believe the Update method will associate an entity with a session other than the one it was fetched with.

Reply to this discussion

Preview Comments are parsed with Markdown. Help with syntax

Attached Files

    You can attach files up to 10MB

    What number comes after 20?