Reputation: 12841
I can't get my head around why this isn't working.. I have two entities with Many-to-many relationships with each other.
public class User : BaseEntity
{
public User()
{
Roles = new List<Role>();
}
[DisplayName("UserName")]
[Required]
[StringLength(20, MinimumLength = 5)]
public virtual string UserName { get; set; }
[DisplayName("Password")]
[Required]
[DataType(DataType.Password)]
public virtual string Password { get; set; }
[DisplayName("Email Address")]
[Required]
[DataType(DataType.EmailAddress)]
public virtual string Email { get; set; }
public virtual IList<Role> Roles { get; set; }
}
public class Role : BaseEntity
{
public Role()
{
Users=new List<User>();
}
[Required]
[DisplayName("Role Name")]
public virtual string RoleName { get; set; }
public virtual string Description { get; set; }
public virtual IList<User> Users { get; set; }
}
public class UserMapping : ClassMap<User>
{
public UserMapping()
{
Id(x => x.Id);
Map(x => x.UserName).Not.Nullable().Unique();
Map(x => x.Password).Not.Nullable();
Map(x => x.Email).Not.Nullable().Unique();
Map(x => x.DateCreated);
Map(x => x.DateModified);
HasManyToMany<Role>(mi => mi.Roles)
.Table("UsersRoles").ParentKeyColumn("UserId").ChildKeyColumn("RoleId")
.Cascade.SaveUpdate().Inverse();
}
}
public class RoleMapping : ClassMap<Role>
{
public RoleMapping()
{
Id(x => x.Id);
Map(x => x.RoleName).Not.Nullable().Unique();
Map(x => x.Description).Nullable();
Map(x => x.DateCreated);
Map(x => x.DateModified);
}
}
When I try simple save associations doesn't save :
var role = _roleTask.GetItem(1); // I am sure exist.
var user = _userTask.GetItem(1); // I am sure exist.
user.Roles.Add(role);
userTask.UpdateItem(user);
Can anyone tell me what is the correct way to map this to get NHibernate to actually store the association ?
I use SQLite
Upvotes: 2
Views: 1972
Reputation: 30813
since there is no code for the tasks i post what should work
// UserMap
HasManyToMany(x => x.Roles)
.Table("sometable")
.ParentKeyColumn("User_id")
.ChildKeyColumn("Role_id");
and
// RoleMap
HasManyToMany(x => x.Users)
.Table("sometable")
.ParentKeyColumn("Role_id")
.ChildKeyColumn("User_id")
.Inverse(); // User handels the insert in the link table
and
var user = session.Get<User>(1);
var role = session.Get<Role>(1);
user.Roles.Add(role);
role.Users.Add(user); // not nessessary for NH because inverse is set but good to be consistent
// Flush all changes (in particular the collection changes) to db
session.Flush();
Upvotes: 7