12

他のエンティティを参照するプロパティを持つエンティティがあります (例では ReferenceEntity)。

HQL を使用すると、次のことができます。

select e.ReferenceEntity from Entity e where e.Id = :entityId

NHibernate は、遅延なしで ReferenceEntity インスタンスを提供してくれます。

クエリを使用して、これを実行しようとしています:

Session.QueryOver<Entity>()
.Where(e => e.Id == entityId)
.Select(e => e.ReferenceEntity)
.SingleOrDefault<ReferenceEntity>()

QueryOver を使用すると、Nhibernate は ReferenceEntity を提供しますが、怠惰です。

hql のように、queryover を使用して熱心な読み込みで ReferenceEntity を取得したいと考えています。

ありがとう

4

3 に答える 3

12

提案#1

必要なデータを取得するためにクエリを実行した後、LINQ 操作を少し行うことができます。

var result = Session.QueryOver<Entity>()
    .Where(e => e.Id == entityId)        // Filter,
    .Fetch(e => e.ReferenceEntity).Eager // join the desired data into the query,
    .List()                              // execute database query,
    .Select(e => e.ReferenceEntity)      // then grab the desired data in-memory with LINQ.
    .SingleOrDefault();
Console.WriteLine("Name = " + result.Name);

それは簡単で、仕事を成し遂げます。

私のテストでは、単一のクエリになりました。出力は次のとおりです。

SELECT
    this_.Id as Id0_1_, this_.Name as Name0_1_, this_.ReferenceEntity_id as Referenc3_0_1_,
    q5379349_r2_.Id as Id1_0_, q5379349_r2_.Name as Name1_0_
FROM
    [Entity] this_
    left outer join [ReferenceEntity] q5379349_r2_
        on this_.ReferenceEntity_id=q5379349_r2_.Id
WHERE this_.Id = @p0;

提案#2

もう 1 つのアプローチは、EXISTS サブクエリを使用することです。これは少し複雑ですが、データベース後の操作を必要とせずに、最初に正しい結果を返します。

ReferenceEntity alias = null;
var result = Session.QueryOver(() => alias)
    .WithSubquery.WhereExists(QueryOver.Of<Entity>()
        .Where(e => e.Id == entityId)                 // Filtered,
        .Where(e => e.ReferenceEntity.Id == alias.Id) // correlated,
        .Select(e => e.Id))                           // and projected (EXISTS requires a projection).
    .SingleOrDefault();
Console.WriteLine("Name = " + result.Name);

テスト済み - 単一のクエリの結果:

SELECT this_.Id as Id1_0_, this_.Name as Name1_0_
FROM [ReferenceEntity] this_
WHERE exists (
    SELECT this_0_.Id as y0_
    FROM [Entity] this_0_
    WHERE this_0_.Id = @p0 and this_0_.ReferenceEntity_id = this_.Id);
于 2012-03-20T03:26:17.770 に答える
0

これを試して:

Session.QueryOver<Entity>()
 .Where(e => e.Id == entityId)
 .Fetch(e=>e.ReferenceEntity).Eager
 .Select(e => e.ReferenceEntity)
 .TransformUsing(Transformers.AliasToBean<ReferenceEntity>())
 .SingleOrDefault<ReferenceEntity>()
于 2012-03-15T14:19:22.263 に答える
0

私があなたのことを正しく理解していれば、あなたが必要としているものは次のとおりです。

Session.QueryOver<Entity>()
 .Where(e => e.Id == entityId)
 //!!!
 .Fetch(e=>e.ReferenceEntity).Eager
 .Select(e => e.ReferenceEntity)
 .SingleOrDefault<ReferenceEntity>()
于 2011-03-21T17:27:31.653 に答える