NHibernate 中的预加载子集合和子集合

发布于 2024-08-04 02:53:29 字数 1035 浏览 2 评论 0原文

我在 NHibernate 尝试加载小型数据层次结构时遇到问题。我的域模型如下所示:

class GrandParent
{
    int ID{get;set;}
    IList<Parent> Parents {get; set;}
}

class Parent
{
    IList<Child> Children {get; set;}
}

class Child
{
}

我想加载给定祖父母的所有父母和孩子。此 Linq-to-NH 查询创建正确的 SQL 并按预期加载祖父母:(该示例假设祖父母有 2 个父母,每个父母有 2 个子对象 - 因此总共有 4 个子对象)。

var linq = session.Linq<GrandParent>();
linq.Expand("Parents");
linq.Expand("Parents.Children");
linq.QueryOptions.RegisterCustomAction(c => 
    c.SetResultTransformer(new DistinctRootEntityResultTransformer()));
var grandparent = (select g from session.Linq<GrandParent>()
                   where g.ID == 1
                   select g).ToList();

Assert(grandparent.Count == 1); //Works
Assert(grandparent.Parents.Count == 2); //Fails - count = 4!

grandparent.Parents 集合包含 4 个项目,其中 2 个是重复的。看来 DistinctRootEntityResultTransformer 只适用于 1 层深度的集合,因此 Parent 集合会根据每个父对象拥有的 Child 对象数量进行复制。

是否有可能让 NH 只包含不同的 Parent 对象?

非常感谢。

I've got a problem with NHibernate trying to load a small hierarchy of data. My domain model looks like:

class GrandParent
{
    int ID{get;set;}
    IList<Parent> Parents {get; set;}
}

class Parent
{
    IList<Child> Children {get; set;}
}

class Child
{
}

and I would like to eager load all parents and children for a given GrandParent. This Linq-to-NH query creates the correct SQL and loads the GrandParent as expected: (the example assumes the grandparent has 2 parents who each have 2 child objects - so 4 child objects in total).

var linq = session.Linq<GrandParent>();
linq.Expand("Parents");
linq.Expand("Parents.Children");
linq.QueryOptions.RegisterCustomAction(c => 
    c.SetResultTransformer(new DistinctRootEntityResultTransformer()));
var grandparent = (select g from session.Linq<GrandParent>()
                   where g.ID == 1
                   select g).ToList();

Assert(grandparent.Count == 1); //Works
Assert(grandparent.Parents.Count == 2); //Fails - count = 4!

The grandparent.Parents collection contains 4 items, 2 of which are duplicates. It seems the DistinctRootEntityResultTransformer only works on collections 1 level deep, so the Parents collection is duplicated depending on how many Child objects each parent has.

Is it possible to get NH to only include the distinct Parent objects?

Thanks very much.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

祁梦 2024-08-11 02:53:29

如果您的映射设置为 FetchType.Join,请尝试将其更改为 FetchType.Select。

If your mapping is set to FetchType.Join, try changing it to FetchType.Select.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文