2012-05-08 19 views
0

我有N層體系結構,並且在服務層中,我需要一種方法來僅獲取關聯實體或完整實體的ID。所以在一個會話中,我只需要id,而在其他會話中,我可能需要完整的實體。如何僅加載相關實體的ID

我有兩個實體:

public class ParentEntity 
{ 
    public virtual long Id { get; set; } 
    public virtual IList<ChildEntity> Children { get; set; } 
    public virtual string Name { get; set; } 
    // ... other fields 
} 

public class ChildEntity 
{ 
    public virtual long Id { get; set; } 
    public virtual string Name { get; set; } 
    public virtual string Description { get; set; } 
    // ... other fields 
} 

我一些時間,我需要加載完整ChildEntity(在驗證層),但有時我只需要加載IDS對像這樣在我的服務層:

ParentEntity parent = repository.GetById(someId); 
SendChildIds(parent.Children.Select(x => x.Id)); 

但這樣做將加載ChildEntity完全,我只想要加載的IDS這樣

SELECT parentchild0_.ParentId as ParentId0_, 
    parentchild0_.ChildId as ChildId0_ 
FROM ParentChildEntities parentchild0_ 
WHERE parentchild0_.ParentId0_= 447 /* @p0 */ 

但他做這樣的事情

SELECT pce.ParentId, ce.* FROM ChildEntities ce INNER JOIN ParentChildEntities pce on pce.ChildId = ce.Id WHERE pce.ParentId = 447 

我用FluentNHibernate配置映射。

回答

0

您可以使用投影或映射到只會返回上述要求的另一個實體。

ParentEntity {..., IList<ChildEntity> Children} 
ChildEntity {...} 
ParentEntityLite {...} //mapped w.r.t requirements i.e. no mappings for children 

或通過投影

from parent in _session.Query<ParentEntity>() 
select new {parent.Id, ...}; //projection --> parent.Id 

from parent in _session.Query<ParentEntity>() 
select new ParentEntity(){Id = parent.Id}; // projection --> parent.Id 
+0

感謝卡爾奎爲你解答,但我想,以避免其他類和預測不能從服務層使用。 –

+0

那麼你的存儲庫必須擴展到允許這在你的服務層,我假設這裏的存儲庫是會話的包裝 – kalki

+0

kalki存儲庫的GetById返回ParentEntity。我如何在返回的實體上使用投影?我同意在存儲庫的搜索方法中,我可以返回IQueryble 並使用項目。 –