0

Suppose I have only two classes: Group and User. User has groups and Group has members (instance of users)

 public class User {
    public virtual int id { set; get; }
    public virtual string username { set; get; }
    public virtual IList<Group> groups { set; get; }       
    public User()
    {     
        groups = new List<Group>();
    }
    public virtual void joinGroup(Group group)
    {
        if (this.groups.Contains(group))
            throw new AlreadyJoinedException();
        group.members.Add(this);
        this.groups.Add(group);
    }

 public class Group
{

    public virtual int id { set; get; }
    public virtual string name { set; get; }
    public virtual User administrator { set; get; }
    public virtual IList<User> members { set; get; }
    public Group()
    {
        members = new List<User>();
    }

As you can see the domain it's quite simple. I've already mapped both classes correctly using Fluent NHibernate,

  public class UserMapping : ClassMap<User>
{
    public UserMapping()
    {
        this.Id(user => user.id).GeneratedBy.Identity();
        this.Map(user => user.username).Not.Nullable().Length(50).Not.LazyLoad();
        this.HasManyToMany(user => user.groups).Table("MemberPerGroup").ParentKeyColumn("id_user").ChildKeyColumn("id_group").Not.LazyLoad();           
    }
}

    public class GroupMapping : ClassMap<Group>
{
    public GroupMapping()
    {
        this.Id(group => group.id).GeneratedBy.Identity();
        this.Map(group => group.name).Not.Nullable().Length(50).Not.LazyLoad();
        this.References(group => group.administrator).Not.Nullable().Not.LazyLoad();
        this.HasManyToMany(group => group.members).Table("MemberPerGroup").ParentKeyColumn("id_group").ChildKeyColumn("id_user").Not.LazyLoad();
    }
}

I'm progamming a web application using ASP MVC 4. My problem shows up when a user tries to join group. It doesn't break but it neither works fine (doesn't insert into the table the new row in MemberPerGroup). I'm doing something like it:

        public void JoinGroup(User user,Group group){
        this.userRepository.GetSessionFactory().TransactionalInterceptor(() =>
        {
            user.joinGroup(group);
        }); 
    }

Thanks in advance.

Ivan.

user1953742
  • 123
  • 1
  • 1
  • 4

1 Answers1

0

It seems your mapping has no cascading set?
this.HasManyToMany(group => group.members)
.Table("MemberPerGroup")
.ParentKeyColumn("id_group")
.ChildKeyColumn("id_user")
.Not.LazyLoad()
.Cascade.SaveUpdate();

I'm curious - why do you use GetSessionFactory()? our repositories take an ISession object in the constructor, (injected by autofac, but that's irrelevant) from which we start our queries:

// even better to use a transaction, but this is just a sample
_session.SaveOrUpdate(user);
_session.Flush();

increddibelly
  • 1,221
  • 1
  • 15
  • 25