如何在 NHibernate 中使用无状态会话添加多对多关系?
我有两个使用 NHibernate 映射到数据库的实体:
class Entity1
{
public int Id { get; set; }
public Entity2[] ReferencedEntities { get; set; }
}
class Entity2
{
public int Id { get; set; }
}
对于 Entity1,我还指定了与 Entity2 的多对多关系:
HasManyToMany(x => x.ReferencedEntities);
据我了解,NHibernate 内部表示创建一些关系实体的多对多关系,例如:
class Reference
{
public Entity1 Entity1 { get; set; }
public Entity2 Entity2 { get; set; }
}
我将这些实体添加到使用 NHibernate 无状态会话的数据库如下所示:
using (var session = sessionFactory.OpenStatelessSession())
{
session.Insert(entity1);
foreach (var entity2 in entity1.ReferencedEntities)
{
session.Insert(entity2);
}
}
但我也想添加它们之间的关系。为此,我还需要保存关系实体。如何使用无状态会话添加多对多关系?我是否需要隐式指定关系实体还是有其他方法?
I have two entities mapped to DB using NHibernate:
class Entity1
{
public int Id { get; set; }
public Entity2[] ReferencedEntities { get; set; }
}
class Entity2
{
public int Id { get; set; }
}
For Entity1 I also specify many-to-many relation to Entity2:
HasManyToMany(x => x.ReferencedEntities);
As I understand, internally NHibernate represents many-to-many relation creating some relation entity like:
class Reference
{
public Entity1 Entity1 { get; set; }
public Entity2 Entity2 { get; set; }
}
I'm adding those entities to DB using NHibernate stateless session like this:
using (var session = sessionFactory.OpenStatelessSession())
{
session.Insert(entity1);
foreach (var entity2 in entity1.ReferencedEntities)
{
session.Insert(entity2);
}
}
But I also want to add relation between them. For this, I need to save relation entity as well. How can I add many-to-many relation using stateless session? Do I need to specify relation entity implicitly or there is some another way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无状态会话不会级联操作,因此如果在其他表中执行更改和数组元素的链接,它不会保存这些更改和链接。
不必要的选择通常是缺少/错误代码的标志,例如
UnsavedValue()
或Equals()``GetHashCode()
Stateless session doesnt cascade operations so it wont save changes and links to the arrayelements if they are performed in other tables.
Unnecessary selects are often a sign of missing/wrong code like
UnsavedValue()
orEquals()``GetHashCode()