如何在Fluent NHibernate中全局禁用延迟加载?

时间:2016-08-09 22:16:13

标签: c# nhibernate fluent-nhibernate

我读了很多关于禁用Fluent NHibernate延迟加载的文章,但没有一篇能够正常工作。我想全局禁用延迟加载。任何人都可以让我知道如何做到这一点。

见下文Fluent NHibernate配置:

 _sessionFactory = Fluently.Configure()
            .Database(MsSqlConfiguration.MsSql2008
                .ConnectionString(_connectionString)
                .ShowSql())
            .Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserMap>()
                .Conventions.Add(FluentNHibernate.Conventions.Helpers.DefaultLazy.Never()))
            .BuildSessionFactory();

1 个答案:

答案 0 :(得分:0)

您可以添加全局IReferenceConvention以删除特定外键的延迟加载:

public class AggregateAttribute : Attribute {
}

public class ReferenceConvention : IReferenceConvention, IReferenceConventionAcceptance, IHasManyConvention, IHasManyConventionAcceptance {
    public void Apply(IManyToOneInstance instance) {
        instance.Fetch.Join();
    }

    public void Accept(IAcceptanceCriteria<IManyToOneInspector> criteria) {
        criteria.Expect(x => x.Property != null && x.Property.MemberInfo.GetCustomAttributes(typeof(AggregateAttribute), false).Any());
    }

    public void Apply(IOneToManyCollectionInstance instance) {
        instance.Fetch.Select();
    }

    public void Accept(IAcceptanceCriteria<IOneToManyCollectionInspector> criteria) {
        criteria.Expect(x => x.Member != null && x.Member.IsDefined(typeof(AggregateAttribute), false));
    }
}

使用聚合属性:

public class FirstRecord {
    public int Id { get; set; }
    public int Name { get; set; }
    // Disable lazy load
    [Aggregate]
    public SecondRecord SecondRecord { get; set; }
    // Lazy load
    public ThirdRecord ThirdRecord { get; set; }
}

public class SecondRecord {
    public int Id { get; set; }
    public int Name { get; set; }
}

public class ThirdRecord {
    public int Id { get; set; }
    public int Name { get; set; }
}

此代码将删除任何具有Aggregate属性的属性的延迟加载,如果要为所有属性禁用延迟,则删除此属性并将约定类更新为:

public class ReferenceConvention : IReferenceConvention, IHasManyConvention{
    public void Apply(IManyToOneInstance instance) {
        instance.Fetch.Join();
    }
    public void Apply(IOneToManyCollectionInstance instance) {
        instance.Fetch.Select();
    }
}

使用此代码,nhibernate将通过同一查询中的连接相关记录自动加载多对一关系,并通过单独查询自动加载一对多。

要使用它,简单注册新约定:

.Conventions.Add(new ReferenceConvention())