0

I have to entities:

public class User
{
    public virtual long Id { get; set; }
    public virtual long Name { get; set; }
}

public class Group
{
    public virtual long Id { get; set; }
    public virtual long Name { get; set; }
}

Mapped as follows:

public class UserMapping : ClassMapping<User>
{
    public UserMapping()
    {
        Table("User");
        Id(e => e.Id, t => t.Generator(new IdentityGeneratorDef()));
        Property(e => e.Name, map => map.Length(50));
    }
}

public class GroupMapping : ClassMapping<Group>
{
    public GroupMapping()
    {
        Table("Group");
        Id(e => e.Id, t => t.Generator(new IdentityGeneratorDef()));
        Property(e => e.Name, map => map.Length(50));

        Set(x => x.Users, set =>
        {
            set.Table("UserToGroup");               
            set.Key(key => key.Column("GroupId");
        },
        re => re.ManyToMany(m => m.Column("UserId")));
    }
}

When i delete User entry, from table UserToGroup should be deleted all entries with this user mentioned. When i delete Group entry, from table UserToGroup should be deleted all entries with this group mentioned;

How exactly i need to rewrite my mappings?

Serg Melikyan
  • 369
  • 1
  • 5
  • 7

1 Answers1

0

This is a standard behavior of NH for the noniverse side of the bidirectional association. Noninverse side (one without set.Inverse(true)) is resposible for persisting changes to the join table. To delete object from the inverse side you need to write additional code.

To delete an entity from the noniverse side of many-to-many association is easy, just call session.Delete(entity) and NH will delete entity and all relevant records from the join table. To delete an entity from the inverse side (the one mapped with Inverse(true)) you need to go another way

var user = ... // user do delete
// delete records from join table
foreach (var group in user.Groups)
{
    group.Users.Remove(user);
}
// delete entity
session.Delete(user);

The similar code I saw in Hibernate forums as an answer on the same question.

hival
  • 675
  • 4
  • 5
  • >To delete object from the inverse side you need to write additional code. Additional means more mappings on User side? – Serg Melikyan Feb 06 '12 at 08:01