NHibernate 与 Cascade 的多对多关系
我必须实体:
public class User
{
public virtual long Id { get; set; }
public virtual long Name { get; set; }
}
public class Group
{
public virtual long Id { get; set; }
public virtual long Name { get; set; }
}
映射如下:
public class UserMapping : ClassMapping<User>
{
public UserMapping()
{
Table("User");
Id(e => e.Id, t => t.Generator(new IdentityGeneratorDef()));
Property(e => e.Name, map => map.Length(50));
}
}
public class GroupMapping : ClassMapping<Group>
{
public GroupMapping()
{
Table("Group");
Id(e => e.Id, t => t.Generator(new IdentityGeneratorDef()));
Property(e => e.Name, map => map.Length(50));
Set(x => x.Users, set =>
{
set.Table("UserToGroup");
set.Key(key => key.Column("GroupId");
},
re => re.ManyToMany(m => m.Column("UserId")));
}
}
当我删除用户条目时,应从表 UserToGroup 中删除提及该用户的所有条目。当我删除组条目时,应从表 UserToGroup 中删除提及该组的所有条目;
我究竟需要如何重写我的映射?
I have to entities:
public class User
{
public virtual long Id { get; set; }
public virtual long Name { get; set; }
}
public class Group
{
public virtual long Id { get; set; }
public virtual long Name { get; set; }
}
Mapped as follows:
public class UserMapping : ClassMapping<User>
{
public UserMapping()
{
Table("User");
Id(e => e.Id, t => t.Generator(new IdentityGeneratorDef()));
Property(e => e.Name, map => map.Length(50));
}
}
public class GroupMapping : ClassMapping<Group>
{
public GroupMapping()
{
Table("Group");
Id(e => e.Id, t => t.Generator(new IdentityGeneratorDef()));
Property(e => e.Name, map => map.Length(50));
Set(x => x.Users, set =>
{
set.Table("UserToGroup");
set.Key(key => key.Column("GroupId");
},
re => re.ManyToMany(m => m.Column("UserId")));
}
}
When i delete User entry, from table UserToGroup should be deleted all entries with this user mentioned. When i delete Group entry, from table UserToGroup should be deleted all entries with this group mentioned;
How exactly i need to rewrite my mappings?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是 NH 对于双向关联的非反向端的标准行为。非逆侧(没有 set.Inverse(true) 的一侧)负责持久保存对连接表的更改。要从反面删除对象,您需要编写额外的代码。
要从多对多关联的非世界侧删除实体很容易,只需调用 session.Delete(entity) ,NH 将从连接表中删除实体和所有相关记录。要从反面(用 Inverse(true) 映射的实体)删除实体,您需要采用另一种方式
我在 Hibernate 论坛中看到的类似代码作为同一问题的答案。
This is a standard behavior of NH for the noniverse side of the bidirectional association. Noninverse side (one without set.Inverse(true)) is resposible for persisting changes to the join table. To delete object from the inverse side you need to write additional code.
To delete an entity from the noniverse side of many-to-many association is easy, just call session.Delete(entity) and NH will delete entity and all relevant records from the join table. To delete an entity from the inverse side (the one mapped with Inverse(true)) you need to go another way
The similar code I saw in Hibernate forums as an answer on the same question.