Fluent NHibernate:在映射中急切加载多个集合

Posted

技术标签:

【中文标题】Fluent NHibernate:在映射中急切加载多个集合【英文标题】:Fluent NHibernate: Eager load multiple collections in mapping 【发布时间】:2017-11-01 17:07:00 【问题描述】:

鉴于我有以下具有多个集合属性的实体...

public class Parent 

    public virtual int Id  get; set;  
    public virtual ICollection<FirstChild> FirstChildren  get; set; 
    public virtual ICollection<SecondChild> SecondChildren  get; set; 
 

有没有一种方法可以使用流畅的 NHibernate 同时预先加载这两个属性?或者只是急切地加载与父级关联的所有内容。

如果我有以下作为我的映射...

public ParentMapping()

    Id(p => p.Id).GeneratedBy.Identity();

    HasMany(p => p.FirstChildren)
        .Table("FirstChildren")
        .KeyColumn("Id")
        .Inverse()
        .Cascade.AllDeleteOrphan()
        .Fetch.Join();

    HasMany(p => p.SecondChildren)
        .Table("SecondChildren")
        .KeyColumn("Id")
        .Inverse()
        .Cascade.AllDeleteOrphan()
        .Fetch.Join();

上面的映射导致错误:

'不能同时提取多个包'。

如果我仅在其中一个属性上使用 Fetch.Join(),则在映射中使用它是有效的。

我可以通过使用 ToFuture() 查询来预先加载所有内容,但是,我更愿意在映射中执行此操作。

【问题讨论】:

【参考方案1】:

您需要使用ISet 而不是ICollection 才能使用该功能。

你可以看看here和here。

【讨论】:

有没有不使用 ISet 的方法?好像我在其中一个集合属性上使用 Fetch.Join() 它工作正常。只有在多个属性上使用它时才会出现问题。

以上是关于Fluent NHibernate:在映射中急切加载多个集合的主要内容,如果未能解决你的问题,请参考以下文章

在没有 .hbm 或 xml 文件的 NHibernate Fluent 映射中定义命名查询

如何在Fluent NHibernate中映射受保护的集合?

使用 Fluent NHibernate 映射泛型类

使用 2 种策略通过 fluent nhibernate 映射类层次结构

如何告诉 Fluent NHibernate 不要映射类属性

使用 Fluent NHibernate 和 NHibernate 3 将枚举映射为 Int