Reputation: 1620
How and What type should I cast result
to User
or Role
or Permission
?
A User has Roles and A Role has Permissions
var result = session.Query<User>()
.Where(c => c.UserName == userName)
.FetchMany(c => c.Roles)
.ThenFetchMany(o => o.Permissions);
Upvotes: 1
Views: 628
Reputation: 38608
Methods like Fetch
(for simple properties) and FetchMany
(for collections properties) method will create an join
in the t-sql query executed by nhibernate and fill the property up after the execution. It will avoid the Lazy Loading to the property. But after you call these methods, you still have an IQueryable<User>
(in your case), because you started with it.
To get a result (or make a cast), depend of how you concrete your query linq, for sample:
For a List<User>
, you could call ToList()
:
var result = session.Query<User>()
.Where(c => c.UserName == userName)
.FetchMany(c => c.Roles)
.ThenFetchMany(o => o.Permissions)
.ToList();
// and you could loop it:
foreach (var user in result)
{
// code...
}
For a single User
object, you could call FirstOrDefault()
:
var result = session.Query<User>()
.Where(c => c.UserName == userName)
.FetchMany(c => c.Roles)
.ThenFetchMany(o => o.Permissions)
.FirstOrDefault();
// and you could use this User object,
// but make sure it is not null
if (result != null)
{
// code...
}
You also can change the output using the Select()
to a DTO
object, an anonnymous object, an specific value, etc. For sample, to return an anonymous object (generally to use in a local scope and execute a simple query), using Select()
method.
var result = session.Query<User>()
.Where(c => c.UserName == userName)
.FetchMany(c => c.Roles)
.ThenFetchMany(o => o.Permissions)
.Select(u => new { u.Id, u.UserName })
.ToList(); // or FirstOrDefault();
Upvotes: 2