Fluent NHibernate 多对多插入问题

Fluent NHibernate Many to Many insert issue

我有 UserModel 和 RoleModel。我认为他们可能存在多对多关系,因为用户可以拥有多个角色,而一个角色可以拥有多个用户。我把它设为多对多,但是当我尝试插入一个用户时,出现如下错误:

INSERT statement FOREIGN KEY constraint "FK6209393F7EB4E792" coincided with. "projectcoderwho" database "dbo.roles" column 'Id' There was an overlap in the table. The statement has been terminated.

我搜索了一些,但没有对我有用的东西,或者我看不到东西。 现在有人知道我的问题了吗?

此代码仅有效一次。但是现在我得到了上面的错误。

UserModel.cs:

public class UserModel
{
    public virtual int Id { get; set; }
    public virtual DateTime RegisterDate { get; set; }
    public virtual string RegisterIp { get; set; }
    public virtual string EMail { get; set; }
    public virtual string Password { get; set; }
    public virtual string UserName { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string WebSiteLink { get; set; }
    public virtual string FaceBookLink { get; set; }
    public virtual string TwitterLink { get; set; }
    public virtual string GooglePlusLink { get; set; }
    public virtual string PinterestLink { get; set; }
    public virtual IList<RoleModel> UserRole { get; set; }
    public virtual DateTime LastLogIn { get; set; }
    public virtual string LastLoginIP { get; set; }
    public virtual string About { get; set; }
    public virtual bool IsActive { get; set; }
    public virtual bool IsFreelancer { get; set; }
    public virtual bool IsBanned { get; set; }

    public UserModel()
    {
        UserRole = new List<RoleModel>();
    }

}

RoleModel.cs

public class RoleModel
{
    //will contains as default: Admin,Moderator,Author,User
    public virtual int Id { get; set; }
    public virtual string RoleName { get; set; }
    public virtual IList<UserModel> UsersInRole { get; set; }

    public RoleModel()
    {
        UsersInRole = new List<UserModel>();
    }
}

UserModelMap.cs:

public class UserModelMap : ClassMap<UserModel>
{
    public UserModelMap()
    {
        Table("Users");

        Id(x => x.Id);

        Map(x => x.RegisterDate);
        Map(x => x.RegisterIp);
        Map(x => x.EMail);
        Map(x => x.Password);
        Map(x => x.UserName);
        Map(x => x.FirstName);
        Map(x => x.LastName);
        Map(x => x.WebSiteLink);
        Map(x => x.FaceBookLink);
        Map(x => x.TwitterLink);
        Map(x => x.GooglePlusLink);
        Map(x => x.PinterestLink);
        Map(x => x.LastLogIn);
        Map(x => x.LastLoginIP);
        Map(x => x.About);
        Map(x => x.IsActive);
        Map(x => x.IsFreelancer);
        Map(x => x.IsBanned);

        HasManyToMany(x => x.UserRole).Table("UsersRoles")
            .ParentKeyColumn("RoleId")
            .ChildKeyColumn("UserId")
            .LazyLoad()
            .Cascade.All();
    }
}

RoleModelMap.cs:

public class RoleModelMap : ClassMap<RoleModel>
{
    public RoleModelMap()
    {
        Table("Roles");

        Id(x => x.Id);

        Map(x => x.RoleName);

        HasManyToMany(x => x.UsersInRole).Table("UsersRoles")
            .ParentKeyColumn("RoleId")
            .ChildKeyColumn("UserId")
            .LazyLoad()
            .Inverse();
    }
}

在UserApiController.cs中:

[Route("User/Register")]
[HttpPost]
public string RegisterUser(object regUser)
{
    RoleModel userRole = BlogModule.getUserRole();//Getting "User" role
    UserModel newUser = JsonConvert.DeserializeObject<UserModel>(regUser.ToString());
    string hashedPassword = BlogModule.PasswordToMD5(newUser.Password);
    newUser.Password = hashedPassword;
    newUser.RegisterDate = DateTime.Now;
    newUser.UserRole.Add(userRole);
    newUser.LastLogIn = DateTime.Now;
    newUser.LastLoginIP = newUser.RegisterIp;


    DbOperations.AddNewUserToDatabase(newUser);

    string sonuc = "true";
    return sonuc;
}

AddNewUserToDatabase(UserModel newUser):

public static void AddNewUserToDatabase(UserModel newUser)
{
    using (var session = NHibernateHelper.OpenSession())
    {
        using (var transaction = session.BeginTransaction())
        {

            UserModel currentUser = session.QueryOver<UserModel>()
                .Where(x => x.UserName == newUser.UserName)
                .SingleOrDefault();
            if (currentUser == null)
            {
                session.Save(newUser);
                transaction.Commit();
            }
        }
    }
}

这里的重点是,HasManyToMany映射必须颠倒/颠倒,当从每一面观察时看法。而不是这个:

public UserModelMap()
{
    ...
    // here we go wrong - parent column cannot be same 
    HasManyToMany(x => x.UserRole).Table("UsersRoles")
        .ParentKeyColumn("RoleId")                     // parent column must target User
        .ChildKeyColumn("UserId")                      //   not Role
        ...

public RoleModelMap()
{
    ...
    HasManyToMany(x => x.UsersInRole).Table("UsersRoles")
        .ParentKeyColumn("RoleId")                     // parent column must target Role
        .ChildKeyColumn("UserId")                      //   here is correct
        ...

因此,我们必须切换父键列的 UserModel 映射:

public UserModelMap()
{
    ...
    // switch them
    HasManyToMany(x => x.UserRole).Table("UsersRoles")
        .ParentKeyColumn("UserId") // instead of("RoleId")
        .ChildKeyColumn("RoleId")  // instead of ("UserId")
        ...

public RoleModelMap()
{
    ...  // stays unchanged
    HasManyToMany(x => x.UsersInRole).Table("UsersRoles")
        .ParentKeyColumn("RoleId")
        .ChildKeyColumn("UserId")
        ...