Vitaliy Ulantikov
Vitaliy Ulantikov

Reputation: 10514

How to add many-to-many relation using stateless session in NHibernate?

I have two entities mapped to DB using NHibernate:

class Entity1
{
    public int Id { get; set; }
    public Entity2[] ReferencedEntities { get; set; }
}

class Entity2
{
    public int Id { get; set; }
}

For Entity1 I also specify many-to-many relation to Entity2:

HasManyToMany(x => x.ReferencedEntities);

As I understand, internally NHibernate represents many-to-many relation creating some relation entity like:

class Reference
{
    public Entity1 Entity1 { get; set; }
    public Entity2 Entity2 { get; set; }
}

I'm adding those entities to DB using NHibernate stateless session like this:

using (var session = sessionFactory.OpenStatelessSession())
{
    session.Insert(entity1);
    foreach (var entity2 in entity1.ReferencedEntities)
    {
        session.Insert(entity2);
    }
}

But I also want to add relation between them. For this, I need to save relation entity as well. How can I add many-to-many relation using stateless session? Do I need to specify relation entity implicitly or there is some another way?

Upvotes: 1

Views: 767

Answers (1)

Firo
Firo

Reputation: 30813

Stateless session doesnt cascade operations so it wont save changes and links to the arrayelements if they are performed in other tables.

Unnecessary selects are often a sign of missing/wrong code like UnsavedValue() or Equals()``GetHashCode()

Upvotes: 0

Related Questions