I have a SQL data model that has a hierarchy similar to the following where each indented entity is a one-to-many child of the above entity.
- Building
- Room
- Container
- Item
- Container
- Room
I make a query for an Item by id and join the parent entities up to the Building and filter by a Building id for data scoping purposes.
By default NHibernate adds all of the joined parents' columns to the resulting SELECT statement. The only solution I have been able to successfully use to get around this is to use projection to explicitly set only the Item columns.
I would like to retain the ids of the intermediate entities like Room without having to add properties to the Item model to retain the Room id.
Is it possible to designate entities remain as proxies unless I retrieve a property of an entity that has not been queried? Alternatively, is it possible to retrieve the ids of these parent entities without explicitly using projection?
I have tried using Fetch() to designate how the join should be handled but NHibernate still queries all of the columns of each joined entity. I have tried other fetch modes but they don't seem to do anything different.
var criteria = Session.CreateCriteria<Item>("i")
.CreateAlias("i.Container", "c")
.Fetch(SelectMode.ChildFetch, "i.Container", "c")
.CreateAlias("c.Room", "r")
.Fetch(SelectMode.ChildFetch, "c.Room", "r")
.CreateAlias("r.Building", "b")
.Fetch(SelectMode.ChildFetch, "r.Building", "b")
.Add(Restrictions.Eq("i.ID", itemId))
.Add(Restrictions.Eq("b.ID", buildingId));
var item = await criteria.UniqueResultAsync<Item?>(cancellationToken);