Hello,
I am trying to use HasManyToMany relation with fluent, it compile and
run, but do not insert middle table data.
Here is the mapping:
public class UserMap : ClassMap<User>
{
public UserMap()
{
Table("tb_users");
//LazyLoad();
//DynamicInsert();
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.Name).Length(100).Not.Nullable();
Map(x => x.Login).Length(30).Unique().Not.Nullable();
Map(x =>
x.PasswordHash).Column("password").Length(100).Not.Nullable();
Map(x =>
x.CPFString).Column("cpf").Length(30).Not.Nullable().Unique();
Map(x => x.ExpiratedDate);
Map(x =>
x.EMailString).Column("email").Length(100).Not.Nullable().Unique();
References<UserStatus>(x => x.Status,
"user_status").Not.LazyLoad();
HasManyToMany<Group>(x => x.Groups)
.Table("tb_users_group")
.Inverse()
.ParentKeyColumn("id_user")
.ChildKeyColumn("id_group")
.Cascade.SaveUpdate();
}
}
public class GroupMap : ClassMap<Group>
{
public GroupMap()
{
Table("tb_groups");
//LazyLoad();
//DynamicInsert();
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.Name).Length(100).Not.Nullable();
Map(x => x.Active).Not.Nullable();
HasManyToMany<User>(x => x.Users)
.Table("tb_users_group")
.Inverse()
.ParentKeyColumn("id_group")
.ChildKeyColumn("id_user")
.Cascade.SaveUpdate();
}
}
And the tables:
CREATE TABLE tb_users
(
id INT IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
login VARCHAR(30) NOT NULL UNIQUE,
password VARCHAR(100) NOT NULL,
cpf VARCHAR(30) NOT NULL UNIQUE,
expiratedDate DATETIME DEFAULT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
user_status int REFERENCES tb_user_status(id) NOT NULL
);
CREATE TABLE tb_groups
(
id INT IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL UNIQUE,
active BIT NOT NULL
);
CREATE TABLE tb_users_group
(
id_user INT REFERENCES tb_users(id) NOT NULL,
id_group INT REFERENCES tb_groups(id) NOT NULL,
PRIMARY KEY(id_user, id_group)
);
When I run this code:
User u = new User();
Group g = new Group();
g.Name = "abc teste";
u.Name = "ADM";
u.Login = "admin";
u.PasswordRaw = "1234mudar";
// u.Groups.Add(groupAdmin);
u.Groups.Add(g);
u.CPFString = "123.456.789-01";
u.EMailString = "
as...@fake.com";
u.Status = status;
u.ExpiratedDate =
DatabaseUtils.Instance.GetDateTime(this.session).AddMonths(-1);
UserBusiness.Instance.Save(u, this.session);
I get this result:
NHibernate: INSERT INTO tb_users (Name, Login, password, cpf,
ExpiratedDate, email, user_status) VALUES (@p0, @p1, @p2, @p3, @p4,
@p5, @p6); select SCOPE_IDENTITY();@p0 = 'ADM', @p1 = 'admin', @p2 =
'???u? e?? ?j ?? ??G', @p3 = '123.456.789-01', @p4 = 01/07/2010
20:36:45, @p5 = '
as...@fake.com', @p6 = 1
NHibernate: INSERT INTO tb_groups (Name, Active) VALUES (@p0, @p1);
select SCOPE_IDENTITY();@p0 = 'abc teste', @p1 = False
The problem is, it should insert relation data into tb_users_group,
does't it?
What I'm doing wrong? I checked a lot of internet example, and tried
to change my code a lot but no result so far.
Thank you.
Rúben