This is an example of how I handle these relationships:
public class User
{
private IList<Group> groups;
public virtual IEnumerable<Group> Groups { get { return groups.Select(x => x); } }
public virtual void AddGroup(Group group)
{
if (this.groups.Contains(group))
return;
this.groups.Add(group);
group.AddUser(this);
}
public virtual void RemoveGroup(Group group)
{
if (!this.groups.Contains(group))
return;
this.groups.Remove(group);
group.RemoveUser(this);
}
}
My User
mapping looks like this:
public class UserMap : ClassMap<User>
{
public UserMap()
{
//Id, Table etc have been omitted
HasManyToMany(x => x.Groups)
.Table("USER_GROUP_COMPOSITE")
.ParentKeyColumn("USER_ID")
.ChildKeyColumn("GROUP_ID")
.Access.CamelCaseField()
.Cascade.SaveUpdate()
.Inverse()
.FetchType.Join();
}
}
My Group
mapping looks like this:
public class GroupMap : ClassMap<Group>
{
public GroupMap()
{
//Id, Table etc have been omitted
HasManyToMany(x => x.Users)
.Table("USER_GROUP_COMPOSITE")
.ParentKeyColumn("GROUP_ID")
.ChildKeyColumn("USER_ID")
.Access.CamelCaseField();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…