NHibernate集获取策略

时间:2018-09-19 13:07:18

标签: nhibernate fluent-nhibernate nhibernate-mapping fluent-nhibernate-mapping

我正在将NHibernate与流利的api结合使用,并获得了MainEntity这样的映射:

mapping.References(c => c.Parent1).Not.Nullable().Fetch.Select();
mapping.HasMany(c => c.Children1).Fetch.Select();
mapping.HasMany(c => c.Children2).Fetch.Select();

然后我要像这样查询MainEntity:

var query = Session.Query<MainEntity>().Where(e => e.ID == id);
query.Fetch(e => e.Parent1).ToFuture();
query.FetchMany(e => e.Children1).ToFuture();
query.FetchMany(e => e.Children2).ThenFetch(c => c.Children21).ToFuture();
var entity = query.ToFuture().FirstOrDefault();

并得到了这样的sql查询:

select * from MainEntity
left outer join Parent1 on MainEntity.Parent1ID = Parent1.ID
where MainEntity.ID = @id;

select * from MainEntity
left outer join Children1 on MainEntity.ID = Children1.MainEntityID 
where MainEntity.ID = @id;

select * from MainEntity
left outer join Children2 on MainEntity.ID = Children2.MainEntityID
left outer join Children21 on Children2.Children21ID = Children21.ID
where MainEntity.ID = @id;

select * from MainEntity
where MainEntity.ID = @id;

但是我希望NHibernate首先选择MainEntity,然后根据条件选择Parent1Children1Children2

select *
from Parent1
where ID = @parent1ID;

select *
from Children1
where MainEntityID = @id;
通过首先查询MainEntities选择

@parent1ID@id

请帮我配置映射。

1 个答案:

答案 0 :(得分:0)

您是否尝试过其他LINQ版本?它应该看起来像这样:

Query<Parent>()
.FetchMany(x=>x.Children1)
.FetchMany(x=>x.Children)
.FirstOrDefault(x=>x.Id=param1);

并将子级映射更改为

mapping.HasMany(c => c.Children1);
mapping.HasMany(c => c.Children2);