我无法理解为什么这不起作用.. 我有两个实体,彼此之间存在多对多的关系。
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);
}
}
当我尝试简单的保存关联时不保存:
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);
有人能告诉我映射这个的正确方法是什么让NHibernate实际存储关联?
我使用SQLite
答案 0 :(得分:6)
因为没有任何代码可以发布应该起作用的任务
// UserMap
HasManyToMany(x => x.Roles)
.Table("sometable")
.ParentKeyColumn("User_id")
.ChildKeyColumn("Role_id");
和
// RoleMap
HasManyToMany(x => x.Users)
.Table("sometable")
.ParentKeyColumn("Role_id")
.ChildKeyColumn("User_id")
.Inverse(); // User handels the insert in the link table
和
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();