2

我无法理解为什么这不起作用..我有两个实体之间存在多对多关系。

 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

4

1 回答 1

7

因为我发布的任务没有代码应该工作

// 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();
于 2012-05-31T11:37:01.190 回答